adding content problem - javascript

Here I've got some trouble trying to add content in a page.
<body>
<div id="wrapper">
<div id="nav">
<ul>
<li><span>exercizeI</span></li>
<li><span>exercizeII</span></li>
<li><span>........</span></li>
<li><span>........</span></li>
</ul>
</div>
<div id="content"></div>
</div>
</body>
So I'be tried to use that piece of code and it didn't work
var table1='<table>..some content..</table>}';
$('#nav li a:eq(1)').click(function (){$('#content').innerHTML='habarlaaaa';});
then tried this one
function press(){
var but = document.getElementById('wrapper').getElementById('nav').getElementsByTagName('ul')[0].getElementsByTagName('li')[1].getElementsByTagName('a')[0];
var table1='<table>..some content..</table>}';
var content = document.getElementById('wrapper').getElementById('content');
but.onclick=function(){content.innerHTML=table1};
};
..and it became even worse by giving me:
Uncaught TypeError: Object # has no method 'getElementById'
error
Why is this happening?
BR, Stephan

Using jQuery you can use the html() function like this:
$('#nav li a:eq(1)').click(function (){$('#content').html(table1);});

To add data inside the content div:
$('#content').append("data");
The reason why your second try fails is because you are applying getElementById() to the result of the previous "getElementById()".

In your first Javascript code you were mixing concepts of DOM methods and jQuery code. Please try the following code
$('#nav li a:eq(1)').click(function (){$('#content').eq(0).html('habarlaaaa');});
the difference is that instead of
$('#content').innerHTML = '......';
You should have used
.eq(0).html('habarlaaaa')

Agreed with Vincent, the reasoning is that when you use the jQuery function, $, you don't get a DOM element, but rather you get a jQuery object representing what you've selected. There are a couple ways of doing this, one of which #vincent-ramdhanie has already mentioned. If you want to get at the actual DOM element, you can do either this:
$('#content')[0].innerHTML='habarlaaaa';
or this:
$('#content').get(0).innerHTML='habarlaaaa';
remember: innerHTML is a property of a DOM element, not a jQuery object.

Related

How to get elementsByClassName and then inside getElementById

Hi I'm rewriting a script from jQuery to pure JS and I don't know how else could i write this.I want to get attribute of element inside class 'form-basket' with id 'przecenajs' I know getElementsByClassName returns object of elements, and that's probably why I get the error:document.getElementsByClassName(...).getElementById is not a function
but I'm not into JS that much so i might be wrong
price = document.getElementsByClassName('form-basket').getElementById("przecenajs").getAttribute("data-procent");
That because getElementsByClassName returns a HTMLCollection object.
You probably want to use querySelector function:
document.querySelector('.form-basket #przecenajs')
console.log(document.querySelector('.form-basket #przecenajs').getAttribute("data-procent"));
<div class='form-basket'>
<div id='przecenajs' data-procent="Hello!">
</div>
</div>
or
document.getElementById('przecenajs')
console.log(document.getElementById('przecenajs').getAttribute("data-procent"));
<div class='form-basket'>
<div id='przecenajs' data-procent="Hello!">
</div>
</div>
Resources
document.querySelector()
Document.getElementsByClassName()
You do not have to select the form-basket first. Since IDs should only be used once inside a document, you can simply selct by id like so:
document.getElementById("przecenajs").getAttribute("data-procent");
I assume you are searching for more than only one tag, because if you wouldn't you could just use document.getElementById() so I think these lines do the job you want, you have to manually create the list with all the attributes to replicate the jquery behaviour:
var priceList = [];
document.querySelectorAll(".form-basket #przecenajs").forEach( (element) =>{
priceList.push(element.getAttribute("data-procent"));
});

Array of elements by class - TypeError: $.id is not a function

I'm trying to create an array from the elements of a div that all share a class.
The div's ID is settingsMenu and all of the elements I need to store in the array share a menuOption class.
The JQuery attempt is as follows:
var options = $.id('settingsMenu').getElementsByClassName('menuOption');
When I execute the function with this statement inside, the error I get is:
"Uncaught TypeError: $.id is not a
function"
The $.id seems to be problematic, am I using it wrong?
Dummy HTML:
<div id="settingsMenu">
<input type="text" class="menuOption" />
<input type="checkbox" class="menuOption" />
</div>
If you want to use jQuery, then you don't need to use the pure Javascript functions like getElementsByClassName() as jQuery provides a very easy to use syntax for accessing DOM elements.
You could refactor your code as follows :
// This will retrieve all elements with the class "menuOption" below an element
// with ID "settingsMenu"
var options = $('#settingsMenu .menuOption');
Not totally sure I'd take this approach, nor have I seen this method for selecting an element by ID. Why not just nest the selector with the following?
var options = $('#settingsMenu .menuOption');
JSFiddle Link - demo
Be sure to check out the jQuery ID Selector (“#id”) docs as well as selectors in general

jQuery method to obtain contents of H2 Tag

I have the following HTML:
<div id="new_subscribed_threads" class="block">
<h2 class="blockhead">Subscribed Threads with New Posts: (0)</h2>
I am using the $.get method to obtain the content of another page on the same server. I want to store the contents of the H2 Tag in a variable and I am confused about how to get the H2.
I tried this:
var MyVar = $(results).find("new_subscribed_threads.h2").html();
But I don't think I am on the right track.
is should be like this:
var MyVar = $(results).find("#new_subscribed_threads h2").html();
or
var MyVar = $(results).find("h2.blockhead").html();
But I don't think I am on the right track.
Yes, you're totally off actually. You don't want to use a class selector .h2, but
an id selector
descendant syntax
and an element selector
It is as simple as this:
Find the position of the h2 tag
Access it and get the content via html()
It looks something like:
var s= $('div.block >h2').html();
console.log(s);

JavaScript equivalent to JQuery .next()

Is there a JavaScript method similar to jQuery .next()? I want to find the next element that has the class of "error" relative to the element. I've tried using .nextSibling as a loop but couldn't figure it out. Didn't know if there was an easier way to go about it without jQuery.
For instance, if I have this code:
<div id="section">
<div id="test">test</div>
<span class="info">Information</span>
<span class="error">Error!</span>
</div>
I'm trying to get the next .error class closest to #test, if I have a #section2 and a #test2 I would want to get the .error class closest to #test2 and so on.
The nextElementSibling property returns the element immediately following the specified element, in the same tree level.
Example: Get the HTML content of the next sibling of a list item:
var x = document.getElementById("item1").nextElementSibling
The nextElementSibling property might help.
Best bet would be to search through the jQuery code and see what they did.
http://code.jquery.com/jquery-2.0.3.js
At a glance, I do see some calls to "nextSibling" and "previousSibling."
Also see here:
How to get next element using JavaScript-only?
Hope this helps!
This is the pure javascript for you:
HTML
<div id="nodes">
<div class="error">This is error Node</div>
<div class="nextElement">This is next Element</div>
</div>
Javscript:
var nodes = Array.prototype.slice.call( document.getElementById('nodes').children ),
errorNode = document.getElementsByClassName('error')[0];
var indexOfError = nodes.indexOf(errorNode);
var nextElement = nodes[indexOfError + 1];
alert(nextElement.innerText);
Here is demo
Sounds like you may be looking for document.getElementsByClassName()... if the elements with class=error are not direct siblings in the DOM, then there's not a good way to find them otherwise. It's elementary, but you can just search through the array returned by document.getElementsByClassName('error') until you find your starting element, and then you know the next item in the array will be the next element in the DOM.
See also MDN reference. Won't work in old IE, but works for all modern browsers.

How to clear all <div>s’ contents inside a parent <div>?

I have a div <div id="masterdiv"> which has several child <div>s.
Example:
<div id="masterdiv">
<div id="childdiv1" />
<div id="childdiv2" />
<div id="childdiv3" />
</div>
How to clear the contents of all child <div>s inside the master <div> using jQuery?
jQuery's empty() function does just that:
$('#masterdiv').empty();
clears the master div.
$('#masterdiv div').empty();
clears all the child divs, but leaves the master intact.
jQuery('#masterdiv div').html('');
Use jQuery's CSS selector syntax to select all div elements inside the element with id masterdiv. Then call empty() to clear the contents.
$('#masterdiv div').empty();
Using text('') or html('') will cause some string parsing to take place, which generally is a bad idea when working with the DOM. Try and use DOM manipulation methods that do not involve string representations of DOM objects wherever possible.
I know this is a jQuery related question, but I believe someone might get here expecting a pure Javascript solution. So, if you were trying to do this using js, you could use the innerHTML property and set it to an empty string.
document.getElementById('masterdiv').innerHTML = '';
jQuery recommend you use ".empty()",".remove()",".detach()"
if you needed delete all element in element, use this code :
$('#target_id').empty();
if you needed delete all element, Use this code:
$('#target_id').remove();
i and jQuery group not recommend for use SET FUNCTION like .html() .attr() .text() , what is that? it's IF YOU WANT TO SET ANYTHING YOU NEED
ref :https://learn.jquery.com/using-jquery-core/manipulating-elements/
If all the divs inside that masterdiv needs to be cleared, it this.
$('#masterdiv div').html('');
else, you need to iterate on all the div children of #masterdiv, and check if the id starts with childdiv.
$('#masterdiv div').each(
function(element){
if(element.attr('id').substr(0, 8) == "childdiv")
{
element.html('');
}
}
);
The better way is :
$( ".masterdiv" ).empty();
$("#masterdiv div").text("");
$("#masterdiv > *").text("")
or
$("#masterdiv").children().text("")
$('#div_id').empty();
or
$('.div_class').empty();
Works Fine to remove contents inside a div
You can use .empty() function to clear all the child elements
$(document).ready(function () {
$("#button").click(function () {
//only the content inside of the element will be deleted
$("#masterdiv").empty();
});
});
To see the comparison between jquery .empty(), .hide(), .remove() and .detach() follow here http://www.voidtricks.com/jquery-empty-hide-remove-detach/
When you are appending data into div by id using any service or database, first try it empty, like this:
var json = jsonParse(data.d);
$('#divname').empty();
$("#masterdiv div[id^='childdiv']").each(function(el){$(el).empty();});
or
$("#masterdiv").find("div[id^='childdiv']").each(function(el){$(el).empty();});
try them if it help.
$('.div_parent .div_child').empty();
$('#div_parent #div_child').empty();

Categories