NSS
NSS

Reputation: 795

Find if attribute is inside the script tag

Im using the following code to update inside specific script tag attribute value this is working but if I put an attribute name which is not inside the script it will create new one attribute with this name, how to avoid that that just if the attribute exist update it otherwise do nothing

This is the code

Content.find("#" + 'test-ui-boot').attr("src1", "test");

this is the script for example

<script id="test-ui-boot" src="/tcore.js"  data-aaa-ui-theme="bbb_val" src1="test" </script>

I use JQuery parser, how can I check if the attribute exist before doing this code

Upvotes: 1

Views: 58

Answers (2)

Nadir
Nadir

Reputation: 1819

attr() returns undefined when the attribute does not exist

if(typeof Content.find("#" + 'test-ui-boot').attr("src1") !== 'undefined')
{
   Content.find("#" + 'test-ui-boot').attr("src1", "test");
}

Upvotes: 1

&#201;ric Viala
&#201;ric Viala

Reputation: 616

I don't know about jQuery, but in plain JavaScript, the function .getAttribute() returns null if the attribute does not exist. E.g. you can run the following against this very page :

z = document.getElementsByClassName('question-hyperlink")[0]
>>> <a class="question-hyperlink" href="/questions/36687960/find-if-attribute-is-inside-the-script-tag">

z.getAttribute('href')
>>>> "/questions/36687960/find-if-attribute-is-inside-the-script-tag"

z.getAttribute('theAttributeThatDontExist')
>>>> null

Upvotes: 1

Related Questions