简体   繁体   中英

How to use an XML tag inside a DIV as a JQuery selector

Fiddle: http://jsfiddle.net/0dapo32a/1/

HTML:

<div class="test1">
<office1><a title="98 Tuvalu road" href="/IDD=1603">98 Tuvalu road</a></office1>
</div>
<div class="test1">
<office2><a title="900 Bleek Ave" href="/IDD=23">900 Bleek Ave</a></office2>
</div>
<div class="test1">
<office3><a title="73 Wabash Street" href="/IDD=3">73 Wabash Street</a></office3>
</div>

How can I edit the JQuery to append anchor text based on criteria.

Your selector is looking for direct children of .test1 by using > .

Change to

$(".test1  a");//match any `a` that is descendant of class `test1`

And it works fine

DEMO

The same way you use any other tag name

$(".test1 office1 a")

If you are wanting to target all 3 office tags you will need to do it three times and separate them by a comma

$(".test1 office1 a,.test1 office2 a,.test1 office3 a")

Or just remove the child selector you were using

$(".test1 a")

Though note the last one will select any a tag that is within .test1

jQuery selector with > looks for direct children of the .test1 class. Change it to $(".test1 a") to match all a that are descendant of that class:

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div class="test1"> <office1><a title="98 Tuvalu road" href="/IDD=1603">98 Tuvalu road</a></office1> </div> <div class="test1"> <office2><a title="900 Bleek Ave" href="/IDD=23">900 Bleek Ave</a></office2> </div> <div class="test1"> <office3><a title="73 Wabash Street" href="/IDD=3">73 Wabash Street</a></office3> </div> <script> var vCityState = new Array("| Darien CT", "| Greenwich CT"); $(".test1 a").text(function (index, oldText) { if (oldText.indexOf("900") > -1) { return oldText + vCityState[0]; } if (oldText.indexOf("Wabash") > -1) { return oldText + vCityState[1]; } }); </script> 

jQuery doesn't care if the tag is XML or anything as it looks for it based on the string.

so you can use:

$("div office1").css("backgroundColor","red");

//or
$("div office1").append('<a href="http://google.com">google</a>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM