MaVRoSCy
MaVRoSCy

Reputation: 17849

How to Select a div that has attribute equals to

I have trouble selecting a div's html content by selecting the div based on its attribute value.

My html is this:

<div id="infowrap1" class="widgetInfobox" possition="1" wid="QI" style="">.....</div>
<div id="infowrap2" class="widgetInfobox" possition="2" wid="CP" style="">.....</div>
<div id="infowrap3" class="widgetInfobox" possition="3" wid="PP" style="">.....</div>
<div id="infowrap4" class="widgetInfobox" possition="4" wid="MT" style="">.....</div>

Lets say I want to get the html() of div with possition=1 ... I tried using

var p1=$(".widgetInfobox [possition='1']").html();
alert(p1); 

..but I get 'undefined', where if I alert only $(".widgetInfobox [possition='1']") I get [object Object]. If I select the .text() I get empty string.

How can I do this? Thanks in advance

Upvotes: 2

Views: 360

Answers (5)

Sudharsan S
Sudharsan S

Reputation: 15393

It's not a descendant selector Just Remove the space between the class and attribute.

var p1=$(".widgetInfobox[possition='1']").html();

I think id be unique in your code Let's take with id easily

var p1 = $("#infowrap1").html();

Upvotes: 1

Nishit Maheta
Nishit Maheta

Reputation: 6031

try this

DEMO

var p1=$("[possition='1']").html();
alert(p1);

OR

var p1=$("div[possition='1']").html();
alert(p1);

NOTE : you can use standers attribute name data-possition instead of possition

DEMO

Upvotes: 1

Umesh Sehta
Umesh Sehta

Reputation: 10681

remove space between class and attribute otherwise it will select child element of .widgetInfobox which has attribute possition='1':-

var p1=$(".widgetInfobox[possition='1']").html();
alert(p1); 

Demo

Upvotes: 1

Adil
Adil

Reputation: 148150

Remove space between class and attribute selector, as space will make it descendant selector which will find elements with attribute possition='1' within descendant of .widgetInfobox

Live Demo

var p1=$(".widgetInfobox[possition='1']").html();

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337647

jQuery's sizzle selector engine follows CSS rules. As such, to select an element using multiple clauses you should not add spaces between them. Try this:

var p1 = $(".widgetInfobox[possition='1']").html();

It should also be noted that possition and wid are not a standard attributes of a div element. Using it will mean that your HTML is invalid. You should instead use data-* attributes:

<div id="infowrap1" class="widgetInfobox" data-position="1" data-wid="QI" style="">.....</div>
<div id="infowrap2" class="widgetInfobox" data-position="2" data-wid="CP" style="">.....</div>
<div id="infowrap3" class="widgetInfobox" data-position="3" data-wid="PP" style="">.....</div>
<div id="infowrap4" class="widgetInfobox" data-position="4" data-wid="MT" style="">.....</div>
var p1 = $(".widgetInfobox[data-position='1']").html();

Upvotes: 2

Related Questions