How do I find a specific child element using javascript - javascript

I've just started using javascript and am trying to do the following:
My html doc contains divs and span elements like below.
I want to create a variable which will store the value of my-new-id for a specific div child element.
The only information I have to go on, is that I always know what the span text will be cause it's based on a username.
Therefore, how would I get the value of my-new-id for user1?
I have already figured out how to navigate to the correct div elemenet using the document.getElementById method. I then try to use a jquery selector such as :contains, but get stuck.
Many thanks on advance.
<div id=1>
<span my-new-id=x>user1</span>
<span my-new-id=y>user2</span>
<span my-new-id=z>user3</span>
</div>
<div id=2>
<span my-new-id=x>user10</span>
<span my-new-id=y>user1</span>
<span my-new-id=z>user30</span>
</div>

Using jQuery:
var val = $('span:contains("user1")').attr('my-new-id');
A couple of additional points:
Do not use IDs that begin with a number. This is not allowed in the HTML4 spec, and can cause unexpected behavior in some browsers. Instead, prefix your ID's with an alphabetic string, like this:
<div id="container1">
...
</div>
I would recommend that you use data-* attributes instead of making up non existent attributes. You can make data attributes like this:
<span data-new-id="x">user1</span>
You can then retrieve this value using:
$('span:contains("user1")').data('newId');
Note that the attribute name has been stripped of dashes and camel-cased.

Related

Check if document contains a class similar to the specified string in Javascript

I am trying to find all elements that contain 'ad'.
Such as:
<iframe class="container" /> <!-- False -->
<a class="adp" /> <!-- True -->
<a class="adleft" /> <!-- True -->
<a class="some-other-class" /> <!-- False -->
Could I use a forEach?
I appreciate any help from everyone.
You can simply achieve this with the combination of querySelectorAll and attribute selector by using the [attr*=value] syntax.
The above attribute selector syntax will work like:
Represents elements with an attribute name of attr whose value contains at least one occurrence of value within the string.
The outcome combination of above solution will be something like this:
document.querySelectorAll("[class*='ad']");
Which give you all the elements whose contain ad within their class names. Then you can simply use a simple loop or array helper like Array#forEach to use the outcome. Note that the previous outcome will produce an HTMLCollection which needs to convert into an array before using array helpers, otherwise you can use the traditional for loop over it.
Here how the final code should look like:
const ads = document.querySelectorAll("[class*='ad']");
Array.from(ads).forEach(el => {
console.log(el);
})
<iframe class="container"></iframe>
<a class="adp"></a>
<a class="adleft"></a>
<a class="some-other-class"></a>
NOTE: You always need to properly open and close HTML tags especially iframe. Since it is not assumed as a self-closing tag it will lead to invalid HTML markup.
You can use an attribute selector to get every elements containing ad. You can read more about it here : doc
document.querySelectorAll('*[class*="ad"]');

JS Only apply if condition to relevant item

I have a small group of items as shown below.
<div class="item">
<div class="date">2013-08-08</div>
<div class="headline"><a data="normal" href="#">Title</a></div>
</div>
<div class="item">
<div class="date">2013-10-08</div>
<div class="headline"><a data="special" href="#">Title</a></div>
</div>
If the title has a data attribute of special, I want to make the date bold for that item only.
I have the below code to try and do this.
<script>
if ($(".headline a [data='special']")){
$( ".date" ).wrap( "<b></b>" );
}
</script>
However this makes all items bold if the condition is true.
I am familiar with using this in JS but not sure how to relate it to another div above.
What is the best way to do this?
I am happy to change the html structure if required as well.
Try the following:
$(".headline a[data='special']").parent().siblings(".date").wrap("<b></b>");
The parent() function will select the div.headline for a matching <a> tag; then, siblings(".date") will select children of the parent of div.headline (which are called siblings) that have the date class.
It sounds like you'd like to select the .date element in .item elements which contain .headline a[data="special"] elements.
$('.item:has(.headline a[data="special"]) .date')
will select the correct .date elements for my given assumptions, you can then call .wrap('<b></b>').
Also note: [data] is not a valid [data-*] attribute. You must have a hyphen and a name for custom data attributes.

how can the value of an href attribute be changed using javascript/css?

Assuming that the html contains the following structure:
<div>
text
</div>
<div>
<div>
//<script> or <style> must go here
</div>
</div>
...and assuming that the 'contribution' to the final HTML file can be inserted ONLY at the specified location, and assuming that the markup for the "a" element cannot be modified in any way, is it possible to add javascript or css code that will change the url that the href attribute of the previous "a" element refers to? If so, how?
You could do it without id:
document.querySelector("a[href^='http://the']")
and set the href prop:
document.querySelector("a[href^='http://the']").href=whatever
For a full reference (browser-compatibility) of querySelector see the MDN-Article
Put an id on it, e.g.
<a id="the_a_tag" href="...">...</a>
^^^^^^^^^^^^^^
then the JS is simply
document.getElementById('the_a_tag').href = 'new address goes here';
as long as you put the javascript AFTER the relevant HTML.
And note: CSS is for presentation only. With a few exceptions, it cannot affect the content of document elements, merely how they appear (color/size/position/etc...).
Give the link an id
<a href='...' id='linkToChange'>text</a>
And then access it in your script:
document.getElementById('linkToChange').href='newAddress';
You can do this using something like this:
document.getElementById("abc").href="xyz.php";
You will need to set an ID for the tag, so your tag will look like this:
<div>
text
</div>
<div>
<div>
//<script> or <style> must go here
</div>
</div>

Trying to select a specific node with Dojo

I'm trying to select the text from the name attribute of the anchor element of the last Comment div in the Comments div (i.e. comment_3037) How can I select it?
Here's my html:
<div id="Comments">
<div class="Comment"><!-- last "Comment" element in the div -->
<a name="comment_3037"></a>
<img src="">
<div>
<div class="Stats">Some info goes here</div>
<div class="Body">Comment goes here.</div>
</div>
</div>
</div>
Corrected Version
(dojo.query always returns a nodelist)
This would look something like that:
var nodelist = dojo.query('#Comments > .Comment:last-child > a[name]);'
var value = dojo.attr(nodelist.at(0), 'name');
Explanation: #Comments > .Comment selects all nodes with class Comment inside the node with id Comments. :lastChild reduces this selection to the last child. > a[name] selects all immidiate children of type a with the attribute name.
The second line just gets the value from the name attribute of the node.
You should get the correct element with that, but I haven't tested it.
Have a look at the dojo reference, there are tons of useful functions.
(I don't work at dojo, I just really like it ;) )
Info
http://docs.dojocampus.org/dojo/query
EDIT
To make sure that you get only the node you want (if you add another link with a name attr), you could add a class "thisisthelinkiwant" (or similar ;) ) to the appropiate link and updating the query to 'Comments .thisisthelinkiwant:last-child'.
You might consider reading about css selectors, as they are quite important with this function.

Getting element inner text ONLY when an <img /> tag exists inside using jQuery 's html()

I'm trying to get the html inside several elements like this:
<div class="option s12 pointer"><img class="fl mt2" src="http://web.iboomerang.com/icons/fff/magnifier.png" /> Trainings by date</div>
Is there a way to strip the tag (like PHP's strip_tags does) and leave only "Trainings by date".
Note: I need to avoid using functions like split() or replace(), because of how versatile this app needs to be.
I think you want this: http://docs.jquery.com/Attributes/text
You can use jQuery's text() function:
var text = $('div.option').text();
You can easily replace 'div.option' with whatever CSS selector(s) you need.

Categories

Resources