Select a div by title with jQuery

2019-07-23 20:21发布

问题:

I have a webpage with a div which contains several other divs WITHOUT an ID associated to them:

<div id="container">
<div   title ="jhon" style=" position:absolute; left: 821px; top: 778.44px; width:8px; height:9px; z-index:3;"> </div> 
<div   title ="carl" style=" position:absolute; left: 561px; top: 579.88px; width:8px; height:9px; z-index:3;"> </div> 
</div>

I need to be able to search one of these div by title and then access its style attributes such as left and top.

I am using jQuery but I have no idea on how to select an element by name. I've tried something like:

var c =$('div[title~="john"]');
alert(c);               //I get [object Object]
alert(c.style.left)     // throws an error and is undefined

but it seems not to work.

Any help?

回答1:

alert( $("div[title=\"john\"]").css("left") );
alert( $("div[title=\"john\"]").css("top") );

or, if the name is a variable:

var name = "john";
alert($("div[title=\""+name+"\"]").css("left"));
alert($("div[title=\""+name+"\"]").css("top"));


回答2:

try

$("div[title~=john]"); //no quotations inside

Attribute Contains Word Selector [name~="value"]