Selecting a container DIV from a known link inside [duplicate] - javascript

This question already has answers here:
Getting the parent div of element
(7 answers)
Find the closest ancestor element that has a specific class
(6 answers)
Closed 3 years ago.
I am trying to work out how to select a container by a link contained within it. It looks something like this:
<div>
<p>Some text here</p>
My Link
</div>
I know the value of "My link". However, the div has no ID or class and is not contained within anything except the body.
How could I use javascript to select the div element so I can manipulate it? I've found ways to select the link using the DOM but not the outer div. There are many divs on the page, so I cannot just select div.
Your help is appreciated!

If the only thing you know is that it's a a as a direct child of a div and it contains the text My Link, you can find it by finding all div > a elements and picking the first one that has that text:
const a = [...document.querySelectorAll("div > a")].find(a => a.innerText === "My Link");
(That relies on the fact that NodeList become iterable a couple of years ago; you may need to polyfill that.)
a will now be the first matching a element, or null if none matched.
From there, if you want that element's container, you can use closest with a CSS selector. For instance:
const x = div.closest("CSS selector here");
...or just use parentNode/parentElement as needed.

Related

count number of div by id after dynamically adding more div by sam id [duplicate]

This question already has answers here:
jQuery clone duplicate IDs
(9 answers)
Does jQuery('#id').length always return 1?
(7 answers)
Closed 3 years ago.
on page load i have following div
<div id="row_log">......</div>
at this stage if i do console.log($('#row_log').length); then i get response as 1 which is correct.
however, i have button to clone the same div, which works fine. So if the button was clicked thrice, i would now have :
<div id="row_log">.....</div> original div
<div id="row_log">.....</div> cloned div
<div id="row_log">.....</div> cloned div
<div id="row_log">.....</div> cloned div
yet console.log($('#row_log').length); would still show as 1 instead of 4
The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).
Use class.
Important points :
1. Id's must be unique.
2. In case of duplicate id's JavaScript will always get the first element for you, hence the length 1.
If you are just building a dynamic list or something, you can instead use a class.
......
And then do document.getElementsByClassName(className)

Why does document.getElementsByClassName return an array here? [duplicate]

This question already has answers here:
How to get element by class name? [duplicate]
(4 answers)
Get Element By Classname Script Not Working
(4 answers)
Closed 5 years ago.
Sorry for a stupid question, but maybe someone can explain it to me. On w3school web-site you can find a modal example. And in order to close the modal they use the following line of code:
HTML:
<span class="close">×</span>
Script:
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
Why to use array here? I tried this code without this array and it doesn’t work. I tried to use different indexes in this array and it also doesn’t work.
Why do we use [0] here and how does it exactly work?
According to Mozilla developer documentation, it returns an array of child elements.
Returns an array-like object of all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class names.
In your case, you have only one DOM element having class 'close'. That's why it returns an array of one element.
Because you can assign a class to more than one element in your HTML document. getElementsByClassName does exactly that: An array of all HTML elements which got the given class assigned to them. The [0] picks the first (and in your case only) element from that array.
If you want to give an unique identifier to a HTML element, assign an id to it and use getElementById.
<span id="close">×</span>
var span = document.getElementById("close");

Clear all the contet in class elements using getElementsByClassName [duplicate]

This question already has answers here:
.getElementByClassName not working? [duplicate]
(2 answers)
Closed 7 years ago.
Im trying to make all my div class elements to lose all its content by replacing their current content with nothing "".
document.getElementsByClassName("sprint_column").innerHTML = "";
But nothing happens with the "sprint_column" when im trying to reach the class, However if i try to reach the IDs it works:
document.getElementsById("div3_Score").innerHTML = "";
Here is the code where the Ids and Classes is created:
<div class='sprint_column' id='div3_".$team."'>Sprint 1</div>
Is there any way to clear all content from a class with "getElementsByClassName" or do i have to loop through all ID elements and clear them one by one?
getElementsByClassName returns an array of DOM elements. You need to iterate through them, e.g. via a for loop, and change the innerHTML one by one.

Select all elements except a div and its contents [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
jQuery: Target all except ___?
I've got a script that detects clicks on every element on the page. I'd like that to run on everything except a specific div and its children.
I've tried doing this using the :not selector, but don't really understand how to use that effectively, so I'm not sure if that's the right way to go or not.
Here's some sample code:
<div id="clickme">This is good stuff</div>
<div id="dontclickme">This should not get selected</div>
I'm currently using $("*") for my selector. Is there a way to use that to detect if it's the second div, or any of its children?
You can use .filter() with .closest() to check if element has a certain id or element is a children/descendant of element with certain id...
$('body *').filter(function(i, v) {
return $(v).closest('#dontclickme').length == 0;
})
http://jsfiddle.net/wirey00/7JE7x/
Select all divs, but not .class:
$("div").not(".class")
Works with other selectors too.

jQuery .each(), .find() and .append() only working on the last node? [duplicate]

This question already has answers here:
How to append one jQuery element already in the DOM to another element?
(5 answers)
Closed 3 months ago.
I am writing a Greasemonkey userscript, with jQuery. The segment of code affects forum thread pages, and intends to append a button to the footer of every post.
Assume the button is already a jQuery element $button, this is the code I have:
$('table.posts').each(function() {
//get the name of the poster
profileName = $(this).find('.user').text();
//change the link relative to each poster
$button.attr('href', '/search?user=' + profileName);
//This is the problematic line:
$(this).find('div.postFooter').append($button);
});
I have tested the value of profileName using an alert, and it successfully iterates through and alerts the profile names, but it only appends the button to the last post's footer (with the correct link).
I've tried using a variety of different selectors and ways to traverse the DOM to the required element, but all methods have resulted in the same thing. I'm out of ideas.
Use clone:
$(this).find('div.postFooter').append($button.clone(true));
Everytime you are changing and appending the same $button element.

Categories