How to add text to a DIV from array of DIVs - javascript

Var divs = $(".txt"); this will return a list of divs with a class txt .
I want to add text to a selected div for example :
divs[4].html("Hello World"); this with return error saying divs[4].html is not a function. why ?

When you access a jQuery object by its DOM array index, you get the HTML element, not a jQuery object, which doesn't have the html() function. Use the eq(n) selector instead:
$(".txt:eq(4)").html("Hello World");

The divs[0] is giving you a DOM reference, not a jQuery object. So, pass that to the jQuery function ($() is shorthand for jQuery()):
$(document).ready(function(){
var divs = $('.txt');
$(divs[4]).html('this one');
});
http://jsfiddle.net/userdude/unu8g/
Note as well the use of $(document).ready(), which will wait until the DOM is accessible. $(window).load() will suffice for this as well, although it may fire after onDOMReady.

The non jQuery way:
document.getElementsByClassName("txt")[4].innerHTML = "banananana!";
Just a side note: I'd suggest learning basic browser javascript before moving to libraries.
It will give you an understanding of how such libraries work and will keep you from being 'locked in' to a specific few

Related

Is there a way to modify a specific attribute of every jquery object in one call?

Basically.... I am using this code
var editorLinks;
editorLinks = $(".admin_editor_link.html");
$.each(editorLinks, function(i, link){
$(link).html($(link).attr("data-loadedtext"));
});
And I am wondering if there is some way to do it without the $.each call... like...
editorLinks.html($(this).attr("data-loadedtext"));
I assumed this would work (or some variation of it that I cant remember) but when I tried it all elements html was set to the data-loadedtext of the first element in the array.
Use a function supplied to html():
editorLinks.html(function(){
return $(this).attr("data-loadedtext");
});
The return value of the function is used as the value for html() for each element.
Using your example HTML in comment:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/taesc0tt/2/
Yes, you can, but you'll need to change the name of your class to admin_editor_link because jQuery selector is trying to find elements with both admin_editor_link and html classes. (Unless, of course, you actually looking for elements with both those classes - your question has no HTML code to verify that - in which case you're fine).
<div data-loadedtext="1" class="admin_editor_link"></div>
<div data-loadedtext="2" class="admin_editor_link"></div>
Just use a function to return the result
var editorLinks = $(".admin_editor_link");
editorLinks.html(function () {
return $(this).attr("data-loadedtext");
});
DEMO
DEMO with both classes

Select a div insinde another div with jQuery

So I try to select a div within another div. My html goes like this:
<div id="Stage_game_page1"><div id="cube0">[...]</div><div id="cube1">[...]</div></div>
I want to select my #cube0 within my Stage_game_page specifically, with jQuery or JS.
The goal of the selection is to use it in an loop.
I tried :
var count =$("#Stage_game_page").children().length;
for(i=0; i<count;i++){
$("#Stage_game_page")$("#cube"+i)[...]
}
I don't understand what I'm doing wrong.
var count =$("#Stage_game_page").children().length;
for(i=0; i<count;i++){
$("#cube"+i);
}
This is sufficient to select the "#cube0"/"#cube1"/"#cube2" etc. especially since ids are always unique. To answer the question $("#cube0", "#Stage_game_page")... that is how you select a div in another div
The id attribute should only be used once! I see above that you're using id="cube0" twice. If you want your divs to be recognized in multiple instances, use a class instead (the . instead of the #). Using the same id twice will probably break your script.
I believe for your html, you could use id "cube0", "cube1", etc., as long as you're ok with entering them manually. That should work for the loop you'd like to use.
Loops through each div that starts with the id cube inside Stage_game_page1
$("#Stage_game_page1 > div[id^='cube']").each(function () {
alert($(this).html());
});
JSFiddle
Child Selctor
Starts with Selector
use each() for loop.
$('#Stage_game_page1').children().each(function(index) {
// your code here with index starts from 0
});
or this using jquery attribute starts with selector
$('#Stage_game_page1').find('[id^="cube"]').each(function(index) {
// your code here
});
You need to use .find() or .children() or the like.
The correct jQuery usage would be
$("#Stage_game_page").find('#cube'+i)
to find a div with that id inside the container #stage_game_page
You have duplicate cube0 in your html code..
and i think the look should contain something like that:
$("#cube"+i)[...]
One another solution is:
$("#Stage_game_page1 div[id='cube0']")

Appending to dynamic content

I have a set a dynamically created divs with the same class name. Now I want to append a entirely new div to all of the above mentioned divs.
Say the class name is extra-upper-block
At the end of my page I have this code
<script>
//function call to load dynamic content
</script>
<script>
$('.extra-upper-block').append('<div>New Div</div>');
</script>
This throws an error in chrome's console
Uncaught TypeError: undefined is not a function
But when this code is executed in chrome's console after the page is loaded, it works!
Why doesn't it work even when I load the dynamic content before executing the append command. Help?
Use jQuery class selector.
$(document).ready(function(){
$('.extra-upper-block').append('<div>New Div</div>');
});
Wrap your code in $(document).ready() for jQuery to get the elements available, and include jQuery file reference.
Note : .append() method is a part of jQuery.
Demo
document.getElementsByClassName returns an array-like object, you can't use it like jQuery, you need to access the individual element in a loop. Also, use appendChild on DOM elements, because they don't have an append method (like jQuery does).
Also, you are trying to append a string <div>New div</div>, you can't directly do that with a DOM element, so instead you can create the div element like so:
Demo
var elements = document.getElementsByClassName('extra-upper-block');
for(var i=0; i<elements.length; i++){
var newDiv = document.createElement('div');
newDiv.appendChild(document.createTextNode('New div'));
elements[i].appendChild(newDiv);
}
Note: querySelectorAll has better cross browser support than this. If you have jQuery included you can simply do:
$('extra-upper-block').append('<div>New Div</div>');
As you can see, with jQuery you can append a string directly.
try writing
document.getElementsByClassName('extra-upper-block')[0].appendChild(document.createElement('div'));
Append is a function in jQuery, try this:
<script>
$(function() {
$('.extra-upper-block').append('<div>New Div</div>');
});
</script>

Use a jQuery Selector as a Variable

I am creating a variable that stores an elements ID in the variable. I could write it like this:
var webappData = document.getElementById('web-app-data');
If I wanted to do the same using jQuery I think I would write it like this:
var webappData = $('#web-app-data');
However, when I try that it doesn't work. (Script throws an error because the variable isn't selecting the div with that Id.)
How would I use jQuery to select an element and store it in a variable?
document.getElementById('web-app-data') isn't the same as $('#web-app-data'). The later returns jQuery object, which is kind of an array of HTMLElement objects (only one in your case).
If you want to get HTMLElement, use $('#web-app-data')[0]. Check:
document.getElementById('web-app-data') === $('#web-app-data')[0]; // true
It's ok.. Maybe something else is wrong in your code..
Example:
<div id="web-app-data">
Hello
</div>
<script type='text/javascript'>
var webappData = $('#web-app-data');
alert(webappData.text()); // Hello
</script>
Fiddle
Above code should work just fine. Your problem might be, that jQuery doesn't find any corresponding elements from the DOM since the element has been removed or hasn't been loaded there yet. If you try to
console.log($('#web-app-data'));
that variable, you can check if jQuery actually found anything. jQuery object should have lenght of (atleast) one if corrensponding element is indeed in DOM atm.
That will work and you use just like it was the full JQuery selector.
var elm = $('#webappData');
if (elm.hasClass('someClass')) elm.removeClass('someClass');
return;

Beginner : How to remove a node that contains a specific class using JavaScript

I have a list that every bock is constructed like below. Some of the blocks have a <span class="protected-icon"></span>. I would like to make a really simple greasemonkey plugin that removes that block. So, my question is using Javascript how can I remove/hide the entire block ( <div data-item-type="user" class="js-stream-item stream-item"></div>that contains it?
<div data-item-type="user" class="js-stream-item stream-item">
<div class="user-content-rest">
<span class="user-name">
<span class="protected-icon"></span>
</span>
</div>
</div>
How to do it without jQuery:
var p = document.getElementsByClassName('protected-icon');
for (var i=p.length; --i>=0;) {
p[i].parentNode.removeChild(p[i]);
}
http://jsfiddle.net/sRs4s/1/
UPDATE If you want to remove the entire stream-item block, you have to loop up to it:
var p = document.getElementsByClassName('protected-icon');
var cstr = "stream-item";
for (var i=p.length; --i>=0;) {
var n = p[i];
while(n.className.split(" ").indexOf(cstr)==-1) { // won't work in older browsers
n = n.parentNode;
}
n.parentNode.removeChild(n);
}
http://jsfiddle.net/sRs4s/3/
See Best way to find if an item is in a JavaScript array? if you need to support older browsers.
To hide you can use the .hide() method.
To remove you can use the .remove() method.
Now to target the block you want
// change hide to remove for complete removal from the DOM.
$('.stream-item:has(.protected-icon)').hide();
will hide all the divs with class stream-item that contain an element with class protected-icon
Demo at http://jsfiddle.net/gaby/eeuQd/
Update
Here is a reference on using jQuery with greasemonkey How can I use jQuery in Greasemonkey?
I read that you are trying to use this with twitter page. Twitter is using Ajax requests to load parts of the page (and load new tweets..) so you might need to use an interval to your script that that it gets re-applied periodically..
That is because your code might run before the twitter has actually loaded the tweets in the page..
something like
setInterval(function(){
$('.stream-item:has(.protected-icon)').hide();
}, 2000 ); // 2000 means every two seconds (in milliseconds)
With JQuery you could do the this to hide the block:
$(document).ready(function() {
$('span.protected-icon').hide();
});
Or to remove it:
$(document).ready(function() {
$('span.protected-icon').remove();
});
Use jQuery's closest() and .remove():
$('protected-icon').closest('div[data-item-type="user"]').remove();
You could also hide the element for later use:
$('protected-icon').closest('div[data-item-type="user"]').hide();
I'm not very familiar with Greasemonkey but I noticed you tagged this as jQuery, so I'm assuming you would get use out of a jQuery script.
I would do this in case you want to bring it back at some point:
$('.protected-icon').parents('.js-stream-item.stream-item[data-item-type=user]').css({'display':'none'});
It is simple using jQuery. Add the following in the top area of your greasemonkey script:
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
Then use the following jQuery:
$('span.protected-icon').parents('.js-stream-item').hide();
Update: Sorry, I had a typo. parent should have been parents.
See the question asked here, which is a different question but contains the answer :-)
Remove element by id
edit: assuming you mean pure javascript, if you are using jQuery see all the other answers!
This should work:
$('span.protected-icon').parents('.user-content-rest').remove();
That will find all the spans with the protected-icon class, then traverse the DOM tree until an element with the user-content-rest is encountered and remove that object.

Categories

Resources