Reputation: 8970
I am loading a text string from a database and I need to access the value of an attribute from its parent element.
String:<p lang="en" langDirection="rtl">Stuff and Things</p>
I need to get the value of langDirection
from the above mentioned code. It should always be the first instance of it so I don't need to search the string globally.
I achieved what I needed for my PHP parts of code using the following:
<?php preg_match('/langDirection="(.+?)"/', $request->requestDescription, $matches); echo $matches[1]; ?>
Can anyone recommend a way to do this with JS/jQuery?
Upvotes: 2
Views: 52
Reputation: 10390
You could use parseHTML
as well:
var el = $.parseHTML("<p lang=\"en\" langDirection=\"rtl\">Stuff and Things</p>");
console.log($(el).attr("langDirection"));
more info: https://api.jquery.com/jquery.parsehtml/
Upvotes: 0
Reputation: 4686
Try the method below.
var $theAttr = $("p").attr("langDirection");
alert($theAttr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p lang="en" langDirection="rtl">Stuff and Things</p>
Upvotes: 1
Reputation: 17930
It is very simple using jQuery:
var strFromServer = '<p lang="en" langDirection="rtl">Stuff and Things</p>';
$(strFromServer ).attr('langDirection');
Upvotes: 4