jQuery not able to select element - javascript

I have a div class which is essentially a button that I'm trying to click using jQuery
<div class="tool-button refresh-button icon-tool-button" title="Refresh"><div class="button-outer"><span class="button-inner"><i class="fa fa-refresh text-blue"></i> </span></div></div>
Here is what I tried but the log confirms the length is 0 thus not selected, any suggestions?:
console.log($('.div.tool-button .refresh-button icon-tool-button:first'))
console.log($('.div.tool-button .refresh-button icon-tool-button'))

You had multiple problems with the selector.
Remove . before div since its a tag not a class.
Remove the spaces between the classes, when there is space between them jquery is looking for element thats a child to the previous selector.
console.log($('div.tool-button.refresh-button.icon-tool-button:first').length);
console.log($('div.tool-button.refresh-button.icon-tool-button').length);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tool-button refresh-button icon-tool-button" title="Refresh">
</div>

In your solutions, you trying to get:
<div class="tool-button">
<div class="refresh-button">
<div class="icon-tool-button"> // this
</div>
</div>
</div>
If you delete spaces on string, you can access your element.
The solution is
$(".tool-button.refresh-button.icon-tool-button")
Chaining selectors will query for elements that contain all of the selectors.
Detailed answer: https://stackoverflow.com/a/59406548/11969749

You can use click() method
const btn = $(".tool-button.refresh-button.icon-tool-button");
btn.click();
Do you want to select first element?
const btn = $(".tool-button.refresh-button.icon-tool-button")[0];
btn.click();

Related

How can you manage CSS selectors for identical code included multiple times in the same page?

I frequently create web apps that use traditional tabs at the top of the page. When doing this, I have a common problem I have been unable to find an elegant solution to.
The problem is the user can load the same content in two separate tabs on the same page. Any HTML ID's on these two different tabs then conflict, causing any JavaScript referencing one of those ID's to fail on the second tab. In addition, any JavaScript referencing a class on one of these pages will affect elements on all tabs, when I really only want it to affect the current tab.
For example, what if I included this block of code twice in the same page?
<style>
#container { margin; 20px; }
#message { background: red; }
</style>
<div id='container'>
<span id='message'>This was from an include file</span>
<button id='changeColorBtn'>Change color</button>
</div>
<script>
$('#changeColorBtn').click(() => $('#message').css('background', 'blue'))
</script>
JSFIDDLE to illustrate the problem: https://jsfiddle.net/dillydadally/2njcq9py/
I have tried or considered three approaches to solve this in the past:
I tried appending a page id to every element in the included content using PHP. This become messy quick and annoying to write out.
I tried making each tab an iframe. At first, this seemed to work well, but quickly became a management nightmare having that many iframes open on the same page that sometimes needed to communicate with each other and share data. I ran into multiple issues and decided not to attempt this approach again.
I considered wrapping each instance of included content in a single element with a unique ID, but I decided I would run into similar issues as option 1 above. Every CSS selector would have to have that element with the ID first, yet again creating messy code and possibly slowing the page down with numerous multi-depth JQuery selectors. In addition, there would still be multiple elements with the same ID on the same page (although I'm not sure that would matter since every selector should have a parent element included).
Is there an element or approach created to address this problem already in HTML/CSS that I'm missing?
You must use a class instead of an ID on an element with the same styling used more than once that you wish to affect with the same css style rule in your document.
For example:
<div id="main"><!-- / The main ID is only used once in the document / -->
<p class="par">
Here is the first paragraph with the same style as the second
</p>
<p class="par">
Here is the second paragraph with the same style as the first
</p>
</div>
Now to your issue of affecting the same type of element used multiple times in your document...
Because you have both the span (message) and button together as a pair under the same parent element, you can access the index of a loop within an event listener to identify the one being pressed using the nodelist being selected.
I use vanilla JS querySelectorAll() on the node list. You must use classes for multiple elements of the same tag name.
I targeted the elements parent class let message = document.querySelectorAll('.content span') and let btn= document.querySelectorAll('.content button'). Then you run the nodes through a forEach loop and add an eventlistener to the button element using the index in the forEach loop. Though this index is the index for the btn element, because these are paired up it will target the correct message element using the index from the btn.
let btn = document.querySelectorAll('.container button');
let message = document.querySelectorAll('.container span');
btn.forEach((button, i) => {
// in short....
// each time the loop iterates the nodelist of btn, it assigns the keyword
// `button` to that iteration of the elements nodelist, so when we click a specific
// `button` it refers to the button being pressed at that time and not all of them
button.addEventListener('click', (e) => {
message[i].style.backgroundColor = 'blue';
})
})
.container span {
background: red;
}
<div id='tab1'>
<div class='container'>
<span>This was from an include file</span>
<button>Change color</button>
</div>
</div>
<div id='tab2'>
<div class='container'>
<span>This was from an include file</span>
<button>Change color</button>
</div>
</div>
Using Jquery: Use $.each to run the list through a loop and use $(this) on a click event and target the elements previous sibling which is the grouped pair within the parents span tag (message).
let btn = $('.container button');
let message = $('.container span');
$.each((btn), function(){
$(this).click(function(){
$(this).prev().css("background-color", "blue")
})
})
.container span {
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='tab1'>
<div class='container'>
<span>This was from an include file</span>
<button>Change color</button>
</div>
</div>
<div id='tab2'>
<div class='container'>
<span>This was from an include file</span>
<button>Change color</button>
</div>
</div>

JavaScript/jQuery detect if div contains text excluding children

I need to verify if a DIV has some text or not inside of it BUT NOT inside its children, eg see this example
<div id='one'>
<div id='two'>Abc</div>
</div>
<div id='three'>xyz
<div id='four'></div>
</div>
If I hover/click element one I want to get false (no text), but if i hover element three I want to get true
i tried using
$('#one').text().trim().length > 0
but it seems to check also any children which is want I do not want to happen
This is already answered here: jquery - get text for element without children text
Also mentions using a plugin to accomplish getting only the text of the element and not child elements here: http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/
This meets your requirements
window.onload=function(){
var two = document.getElementById('two').textContent;
console.log(two.trim()=='');
var three = document.getElementById('three').textContent;
console.log(three.trim()=='');
}
<div id='one'>
<div id='two'>Abc</div>
</div>
<div id='three'>
<div id='four'></div>
</div>

How to remove div with a particular text in it

I have some div tags which has some text & elements in it & I want to remove those div's, They are looks like this
<div style="font-family:verdana;font-size:12px;">
Example
example
</div>
There are many div's like this & I want to remove them all with using jQuery or javascript
If the elements have nothing in common such as a class, you can remove it by using the :contains and remove() method.
$("div:contains('Example')").remove()
Full example shown below:
$("div:contains('Example')").remove()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div>
Example
</div>
<div>
Darren
</div>
If the elements do have something in common you could use the class selector.
$(".common-class").remove();
Based on Darren's answer, if you want to be extra sure (as :contains will match and delete any div containing the word example), you can make sure it's a div that has an anchor with that same example as children, then go back to the parent and remove it.
If this doesn't work, please paste a few more divs so we can see a common pattern and target it the safest way possible.
$(document).ready(function(){
$('#remove').click(function(e){
$("div:contains('Example')").children("a:contains('example')").parent("div:contains('Example')").remove()
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="font-family:verdana;font-size:12px;">Example example</div>
<div style="font-family:verdana;font-size:12px;">Don't remove example</div>
<div style="font-family:verdana;font-size:12px;">Example don't remove</div>
<button id="remove">
Remove undesired divs
</button>

How can I remove a class from the span nearest span using jQuery?

I have a page that allows visitors to add favorites to a list. It uses repeating rows to show items so generic classes are repeated.
How can I show a single modal window (.closest or .prev?) if they all have the same class?
Here is my fiddle: http://jsfiddle.net/psasj74L/
<span class="jsCrateMaxModal most-wanted-modal-container hide">
<div class="most-wanted-modal">
<div class="most-wanted-content">
One.
<div class="col-xs-12">
<div class="btn-primary btn-block">OK</div>
</div>
</div>
</div>
</span>
<button class="jsShowMaxModal mostWantedOff">Show Modal</button>
jQuery:
$('.jsShowMaxModal').click(function () {
$(".jsCrateMaxModal").closest("span").removeClass("hide");
});
$('.most-wanted-modal-container').click(function () {
$('.jsCrateMaxModal').addClass("hide");
});
You can use .prev() in this case to find the modal preceding the button.
$('.jsShowMaxModal').click(function () {
$(this).prev(".jsCrateMaxModal").closest("span").removeClass("hide");
});
Working example: http://jsfiddle.net/psasj74L/2/
However, this is a little flaky, and I would recommend wrapping the span and button in a div which offers some logical grouping. If this is not possible, an alternative is to use data attributes to specify which modal a button should open.

Hiding many divs with one onclick function

I am looking for a Javascript solution for this problem. I have the following HTML:
<div id = "container">
<div id = "data">
<div>
<h3> Address</h3>
<b>Expand...</b>
<div id="content">ul. Pomorska</div>
</div>
<div>
<h3> Telefon </h3> <b>Expand...</b>
<div id="content">26565352</div>
</div>
<div>
<h3>Email</h3>
<b>Expand...</b>
<div id="content">asdasdag#aga.com</div>
</div>
</div>
</div>
I would like to hide the content div when an onclick Expand is made. So far I have made a function which hides the content divs and tries to assign an event handler to the node.
function hideinfo() {
var node = document.getElementById("data");
var contactdata = node.getElementsByTagName("div");
for(var i=0; i<contactdata.length;i++) {
if(contactdata[i].id == "content") {
alert(contactdata[i].previousSibling.innerHTML);
contactdata[i].previousSibling.addEventListener('click',ShowHide,false);
contactdata[i].style.display="none";
}
}
}
The problem is that the alert displays undefined. Why can't it see the node? Is there a better way to do this in Javascript?
Because previousSibling is most likely the text node before the div element. You probably want to use previousElementSibling instead :)
In most browser today, querySelectorAll, which lets you use CSS selectors for finding elements, is also a good alternative (IE8+)
The previousSibling property returns the previous sibling node (the previous node in the same tree level) of the selected element
which returns in your case the TEXT node.
As you can see in this jsfiddle: http://jsfiddle.net/Xu383/
alert(contactdata[i].previousSibling.nodeName);
You are better of using the querySelectorAll.
Also you can't have multiple divs with the SAME id, use class instead.

Categories