jQuery selectors for dynamically loaded HTML [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 years ago.
jQuery does not seem to be able to select a loaded HTML element. Here is my HTML:
<div class="class name" style="display: none;">
<div id="submenuID" class="submenuID" />
<script>
loadHtmlUsingJavascript('parameter1', 'parameter2');
</script>
</div>
The loaded HTML is a list of links. This is my JavaScript:
$("#submenuID li").addClass("active");
But it would not add the class. After some snooping around. I learn to use
$("#submenuID li").live('click', function() {
$("#submenuID li").addClass("active");
});
However, it does not work until I click on the link a second time.

You have to do the following:
$("#submenuID").on('click', 'li', function() {
$(this).addClass("active");
});
First, the jQuery .live function is deprecated since jQuery 1.7 (http://api.jquery.com/live/)
Also, you should be listening for li methods inside the #subMenuID element.

Related

How do I have a function find two elements? [duplicate]

This question already has answers here:
Can you do an 'AND' on a jQuery selector to target multiple buttons?
(3 answers)
Closed 4 months ago.
I'm a beginner with JavaScript so I'm sure this will be an elementary question.
With this function below, I want it to find the two elements and add them to a header element. Right now, the only thing that is working is the element, the link with the rel:author tag. I'm sure this is probably a syntax thing.
(function($) {
$(document).ready(function() {
$(".single .single-post-module").each(function() {
$(this).find('a[rel="author"]', 'span[class="updated"]').clone().appendTo($(this).find('.post-header h1'));
// ^^^
});
});
})(jQuery)
Edit: I'm using Divi on wordpress and the site is in maintenance mode. That's why didn't show the HTML or give a link.
This could be done with pure Javscript querySelectorAll with an CSS selector that will find both elements.
To clone the element, use cloneNode(true) where the first parameter indicates to clone 'deep'
const header = document.querySelector('.post-header > h1');
const elements = document.querySelectorAll('.single, .single-post-module');
Array.from(elements).forEach(e => header.append(e.cloneNode(true)));
<div class='single'>
<a rel='author'>Link</a>
<span class='updated'>Span</span>
</div>
<div class='single-post-module'>
<a rel='author'>Link</a>
<span class='updated'>Span</span>
</div>
<div class='post-header'>
<h1></h1>
</div>

.change() jquery event not working on dynamically created input elements [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 2 years ago.
I am having a input of type = " file " on my page. Also I have a button "Add Inputs" on the page which adds a new file input element on page and I want to run a function when user changes the value of any of those inputs by selecting a new file.
Here is my code.
HTML
<div class="main">
<div id="InpDiv">
<input type="file" name="fname">
</div>
</div>
<div>
<button onclick="addInp()">Add Inputs</button>
</div>
JS
// Function that is going to run after change in file input.
$(document).ready(function(){
$("input[name='fname']").each(function(){
$(this).change(function(){
alert('hello');
// Do some work here.
});
});
});
// Function that adds new file inputs.
function addInp()
{
$('#InpDiv').clone().appendTo(".main");
}
Now the problem is .change() method works fine for those inputs which were present already on page but not works (won't prompt "hello" message here) on change of values in those newly created inputs. I made more than one file inputs already present on page and .change() worked for all of them but it didn't worked for any of the newly created inputs.
Is it so that events won't work with dynamically added elements on page ?
And if so then how am I going to get this work done?
Try delegation approach using .on(). This will ensure that events will be attached to all the elements that are added to the DOM at a later time.
Also I will prefer using input event instead of change:
Change:
$(this).change(function(){
To:
$('.main').on('input', this, function(){
$(document).ready(function(){
$("input[name='fname']").each(function(){
$('.main').on('input', this, function(){
alert('hello');
// Do some work here.
});
});
});
// Function that adds new file inputs.
function addInp()
{
$('#InpDiv').clone().appendTo(".main");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
<div id="InpDiv">
<input type="file" name="fname">
</div>
</div>
<div>
<button onclick="addInp()">Add Inputs</button>
</div>

Remove the contents under classname using Javascript [duplicate]

This question already has answers here:
Remove all child elements of a DOM node in JavaScript
(37 answers)
How do I clear the content of a div using JavaScript? [closed]
(2 answers)
Closed 5 years ago.
I want to remove the everything under the classname: social-share using JavaScript
HTML: This is what it looks like when I grab the code from chrome inspector.
<div class="social-share">
[shareaholic app="share_buttons" id="26444890"]
</div>
HTML: This is what exactly looks like inside the chrome inspector
<div class="social-share">
"
[shareaholic app="share_buttons" id="26444890"]
" == $0
</div>
You can use innerHTML to clear the contents of the element after it has been selected:
// select element with class 'social-share:
var social_share = document.querySelector('.social-share');
// Set it's contents to an empty string
social_share.innerHTML = '';
$('.social-share').empty();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="social-share"> content
<div>content</div>
</div>
Jquery empty() might be help you. It will remove every thing inside social-share class

jquery show() not work unless invoke alert after that [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 8 years ago.
i use jquery.show() to display a div, but I cannot see the display effect, unless invoke alert after show method like this:
JavaScript:
$("#screenAsLayer").show();
$("#screenAsLayer_content").show();
alert("aa");
HTML:
<div id="screenAsLayer" class="screenAsLayer"></div>
<div id="screenAsLayer_content" class="screenAsLayer_content">
<img src="..../img/....gif">
</div>
CSS:
.screenAsLayer{
display:none;
z-index:9;
position:abosolute;
}
.screenAsLayer_content{
display:none;
z-index:10;
position:abosolute;
}
JSFiddle Demo
Try this out:
$(document).ready(function() {
$("#screenAsLayer").show();
$("#screenAsLayer_content").show();
});
Working Fiddle

jQuery on method with ajax response [duplicate]

This question already has answers here:
Event handler not working on dynamic content [duplicate]
(2 answers)
Events triggered by dynamically generated element are not captured by event handler
(5 answers)
Closed 9 years ago.
I have a <select class="listenToMe" /> that when changes does something. I also have a separate link that when clicked performs an ajax request and returns more dom elements and inside them it has another <select class="listenToMe" />
I would like my event listener to be applied to this element as well. I am trying to use jQuery's on method but it doesn't appear to be working:
JS
var selectListener = function() { alert('you change me!'};
$('.listenToMe').on("change", selectListener);
$('.addMore').click( function() {
$.post('myWebPage.php', {} , (function(data) {
$(this).before(data);
// data is something like <div><select class="listenToMe" /></div>
}).bind(this));
});
HTML
<div>
<div>
<select class="listenToMe" />
</div>
<div>
<select class="listenToMe" />
</div>
<a class="addMore">Click me</a>
</div>
Any suggestions?
You can try
$(document).on('change', '.listenToMe', function(){
// Your code here
})
Your using on like live. The difference is subtle but important. You attach on to a static element in your markup and then filter the event based on a selector. This way the on event never goes out of scope, e.g. if I have the markup
<!-- this div is not dynamically loaded-->
<div id="mystaticDiv">
<!--insert dynamic content here-->
</div>
which when I add my dynamic markup will become:
<!-- this div is not dynamically loaded-->
<div id="mystaticDiv">
<!--insert dynamic content here-->
<div class="myDynamicdiv></div>
</div>
To fire an event on the click of my dynamic div that never needs rebinding I would write the following jQuery:
$('#mystaticDiv').on('click', '.myDynamicdiv', function() {/*Do stuff*/});
So I'm binding my on to the #mystaticDiv but filtering on .myDynamicdiv. Now I can add as many .myDynamicdivs as I want and this will work.
I mentioned live. This is deprecated but works in the same way as you were attempting. This attaches an event to the document of the page with a selector base on the selector your attaching live to. So $('.myDynamicdiv').live('click', function() {/*Do stuff*/}); is directly equivalent to $(document).on('click', '.myDynamicdiv', function() {/*Do stuff*/});. the reason I mention this is this is how you were trying to use on.
Your code $('.listenToMe').on("change", selectListener);. Will not work for dynamic content. This code attaches the event to the dynamic content, that doesn't exist yet. So the is never actually bound. Interestingly $('.listenToMe').on("change", selectListener); is exactly what $('.listenToMe').change(selectListener); does under the hood.

Categories