Javascript: Remove Child when using document.write - javascript

I want to have something like this:
var abc1 = document.write('<html>HTMLPAGECONTENTHERE</html>');
function removepage(){
abc1.parentNode.removeChild(abc1);
}
removepage();

That won't work; document.write doesn't return anything.
You should use the DOM APIs instead (createElement() and appendChild()), or, more easily, jQuery.

document.write inserts a stream of HTML directly into the page. It has no useful return value.
If you want to manipulate what it outputs via DOM, then you have to have a known quantity to match with getElementById, getElementsByTagName or some other method for getting HTML Element Nodes from a DOM.

Related

Why is innerHTML returning 'undefined'?

I'm trying to catch the "value" inside this div, which is editable:
<div class="editable-div" contentEditable="true">Hey</div>
I figured I could do this simply via JavaScript:
var changedText = $('.editable-div').innerHtml
However, this variable will always return "undefined", which confuses me.
Can someone enlighten me on how to reach this "value"?
It is jQuery - you have to use:
$('.editable-div').html()
A jQuery wrapped object is actually not the raw DOM node, but essentially an array of raw DOM nodes that can be acted upon with jQuery specific methods, such as .html(). If you want to interact with the DOM node, you can retrieve it by either iterating through the list or getting the element of that list if you know which one it is:
$('div').each(function(index, element) {
element.innerHTML // ...
}
$('div').get(0).innerHTML
$('div')[0].innerHTML
Note that while it is "kind of" like an array, in that you can get DOM nodes using the array syntax of $('div')[0], you can't treat it like an array in Javascript. In other words, you can't do this:
$('div').forEach(function(element) {
element.innerHTML
}
innerHtml is used with javascript selector and you are using jQuery. so replace innerHtml with .html() or .text() function.
Use this:
var changedText = $('.editable-div').html();
innerHtml is DOM. try $('.editable-div')[0].innerHtml

Javascript DOM Document createElement from tag source

Is there a way to create a new element in a Document object from the tag source? Essentially what I'd like to do is something to effect of:
myDocument.createElement('<sometag attr="lol">');
No, native DOM API for .createElement doesn't support that syntax. You need to create the plain Element and set any property either directly on the object
newElem.attr = "lol";
or (better), use .setAttribute()
newElem.setAttribute( 'attr', 'lol' );
What you "could" do is do create a documentFragment, then use .innerHTML to write that string into that fragment and finally .append its contents to its target destination.
well, use innerHTML instead of trying to hack dom manipulation for this kind of thing.
To do so, create a valid node with dom if you want (or get it via getElementById), then set innerHTML of this node with your code
The innerHTML property works here - but it's a tad bit difficult to place the thing where you want it sometimes. For example:
var div = document.createElement('div');
div.innerHTML = "<img src='http://www.google.com/logos/classicplus.png'/>";
In my humble opinion, it's a heck of a lot easier to use jQuery to handle it for you, as it comes with all of the jQuery methods already attached.
var div = $("<div class='blah'><img src='http://www.google.com/logos/classicplus.png'/></div>");
div.find('img').hide();
div.appendTo('body');
div.find('img').fadeIn();

Getting a single element with `getElementsByTagName`

I know that if we want to find a group of elements, getElementsByTagName is the method for us and it returns a NodeList. but if we are looking for tag name with "body" , then why we need to add [0] after the ("body") element? There is only one body tag in an HTML document.
var body = document.getElementsByTagName("body")[0];
body.className = "unreadable";
why we cant write this code without index[0] like this
var body = document.getElementsByTagName("body");
body.className = "unreadable";
If i write this code the class unreadable will not be added with body tag ...why?
Because document.getElementsByTagName allways returns NodeList. If you want find easier way to retrieve body you can use just document.body
getElementsByTagName returns a NodeList. It might have no items in it. It might have one. It might have many. You can see how many are in it by testing its .length.
It would be confusing if it sometimes returned a NodeList and sometimes returned an ElementNode.
getElementsByTagName [docs] always returns a NodeList. It does not matter whether an element with a certain tag exists only once.
It would be bad if the function behaved inconsistently.

bookmarklet: inserting text into textarea with js?

What I am doing wrong?
javascript:document.getElementsByTagName('textarea').innerHTML='inserted';
I want to create a bookmarklet to insert simple text to a textarea on a given webpage.
Use the value property rather than innerHTML and make sure your code evaluates to undefined, which you can do by wrapping it in a function with no return statement. If you don't do this, the contents of the page will be replaced with whatever your code evaluates to (in this case, the string 'inserted').
javascript:(function() {document.getElementsByTagName('textarea')[0].value = 'inserted';})();
Update 14 January 2012
I failed to spot the fact that the original code was treating document.getElementsByTagName('textarea') as a single element rather than the NodeList it is, so I've updated my code with [0]. #streetpc's answer explains this in more detail.
Unlinke getElementById, getElementsByTagName has an sat Elements because it returns an array array-like NodeList of the matching elements. So you'll have to access one of the elements first, let's say the first one for simplicity:
javascript:void((function(){document.getElementsByTagName('textarea')[0].value='inserted'})())
Also, as mentioned by others, value property rather than innerHTML here.
In case anyone wonders how to use the currently focused text field, use the following:
document.activeElement.value = "...";
In jQuery you have to use if this way:
for single element -> $('#element_id').html('your html here')
for all text areas -> $('textarea').val('your html here')
I have to confess that I`m not sure why it works this way but it works. And use rameworks, they will save you time and nerves.

Weird Behaviour in jQuery's html method

Any good reason why $("p").html(0) makes all paragraphs empty as opposed to contain the character '0'?
Instead of assuming I found a bug in jQuery, it's probably a misunderstanding on my part.
jQuery only accepts a string as an argument for the val parameter of the html() method. If you pass a number like you are it will call the html() method override that sets the contents of the element but the value of the argument will end up being null or an empty string.
Try this:
$("p").html((0).toString())
Relevant documentation
I guess that at some point, it checks if (newContent == false), and doesn't continue with adding any content? I tried looking at the source, but got a bit lost...
I also guess that this would not be counted as a bug, since the function calls for a string, and if "0" is passed (as a string), it works as expected.
A workaround would be to do this:
var myNum = 0;
$('p').html('' + myNum);
The code performing the html call was within someone else's plugin and rather than modify it, making upgrading it tedious, I just wrote the following tiny plugin that modifies the html method to do as spoon16 recommended.
(function($) {
var oldHtml = $.fn.html;
$.fn.html = function (content) {
oldHtml.apply(this, [content.toString()]);
}
})(jQuery);
It's a little bit of a hack, but it's working for me and doesn't require me to modify the Plugin I'm using.
I just thought someone else might like to see this.
Try using text() instead html().
I geuss you missed part of how jQuery works,
$('p')
returns all paragraphs and the html( val ) function:
Set the html contents of every matched element. This property is not available on XML documents (although it will work for XHTML documents).
http://docs.jquery.com/Attributes/html#val
So if you just want to set the contents for the first p use
$("P").eq(0).html( 'something' );
or to get the html:
$("P").eq(0).html();
http://docs.jquery.com/Core/eq#position
more on jQuery selectors here:
http://docs.jquery.com/Selectors

Categories

Resources