Remove element in JavaScript - javascript

In the below code how to remove the hyperlink after getting the innerHTML:
function test(obj)
{
var a=obj.innerHTML
//remove obj element here
}
$p = $('<a id="name" onclick="var ele=test(this);">').html( "test" );
$('#questions').append( $p );

You can remove an element using the DOM method removeChild. If you start with a reference to the child [as you seem to in your test function (the obj argument)], you can remove it like this:
obj.parentNode.removeChild(obj);
(Your question is also tagged jQuery but I see someone pointed you to jQuery's remove function and you said you didn't want to use that. In any case, for completeness I've noted it here.)

You're using jQuery, so just do:
$(obj).remove()

Related

Unable to select <a> based on its text and then add an attribute named "target" to it using jQuery

I have the following link inside my web page:
Attachments and Documents
Now I want to select this link based on its text "Attachments and Documents", and set a target attribute for it.
So I tried the following:
var tgb = $('a:contains("Attachments and Documents")')[0];
tgb.attr('target', '_blank');
But I got the following exception :
TypeError: tgb.attr is not a function
As soon as you use index ([0]), tab is no more a jQuery object. To get the jQuery function attr() you have to wrap tgb with $:
var tgb = $('a:contains("Attachments and Documents")')[0];
$(tgb).attr('target', '_blank');
// to demonstrate result
console.log(tgb)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Attachments and Documents
attr() is a jQuery function. You need to target your variable using jQuery methods
$(tgb)
Hope this helps :)
var tgb = $('a:contains("Attachments and Documents")')[0];
$(tgb).attr('target', '_blank');
console.log(tgb);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Attachments and Documents
var tgb = $('a:contains("Attachments and Documents")');
tgb.attr('target', '_blank');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Attachments and Documents
The issue with your logic was the [0] that you were putting on the tgb. [0] on a jQuery object breaks the element out of the jQuery object and returns the native Element. There are various reasons why you would want to do this, such as if you wanted to access element properties and you don't want to go through the jQuery prop() or attr() method.
However in your case, you are trying to use the attr() method off of tgb. However, attr() is a jQuery method. Since you broke the element out of the jQuery object, this will not work.
Rather than turning the tgb back into a jQuery object, simply take off the [0]. This fixes your issue, and removes the need to create another jQuery object which, give the snippet you provided, is unnecessary work.
Optionally, if you do want it to be a native Element you could just set the attribute directly.
var tgb = $(...)[0];
tgb.setAttribute('href', newValue);
//or
tgb.href = newValue;

jQuery adding new DOM elements having attributes within an element of specific id

Is there a methodToCreate in jQuery which could be written as
$("#someId").methodToCreate("tagName", ".className");
where an element with tag tagName would be added and given a class className and that too inside a specific element which would have an id someId?
$("<tag></tag>").addClass("className").attr({id: 'someId'}).appendTo( "body" )
Here's and example setting all the attributes individually.
As pointed out such function doesn't exist, but you could always create one .
(function( $ ){
$.fn.methodToCreate= function(tagName,className,id) {
$(id).append("<"+tagName+" "+"class="+"\'"+className+"\'>"+"SampleContent"+"</"+tagName+">");
return this;
};
})( jQuery );
and you can call this whenever you want in the following manner :
$(document).ready(function(){
$(document).methodToCreate('p','sampleClass','#someId');
});
Using this function(methodToCreate) you can dynamically pass the tagName , className and id of the element that you want to append to.
Here is the working fiddle : https://jsfiddle.net/varunsinghal65/udrxeg9m/1/#&togetherjs=TBEnLAnNzJ
Using jQuery you can create an element
var el = $('<tagName class="className"/>');
and then add it to a container
$('#someId').append(el);
$('#someId').append('<tagname class="className"></tagname>');
if you have the class stored in a variable (for example myClass) don't forget to quote it like this:
$('#someId').append('<tagname class="' + myClass + '"></tagname>');
No that method does not exist, but you can use .appendTo
like:
$("<tagName class='className'></tagName>").appendTo("#someId");
Hope it helps.

Put an id to a parent element

I wanted to put an id in my element's parent element. Below is my code:
<div>
<div id="child"></div>
<div>
Im aware that jquery has a way to select a parent element , but I dont know how what method shall I use to put an id to it. Below is my jquery code:
div_resizable = $( "#child" ).parent();
div_resizable.id = "div_resizable";
Above code doesnt work with me. It doesnt throw an error, but no changes had taken effect. Any solution to my problem?
For achieve what you want, you can use the jquery attr:
$("#child" ).parent().attr('id', 'newID');
Or you can use the prop:
$("#child" ).parent().prop('id', 'newID');
And you can check the difference between the two here: difference between prop() and attr()
Of course div_resizable.id = "div_resizable" doesn't work. div_resizeable is an jQuery array and you are trying to assign id to it.
Try .attr instead:
$("#child").parent().attr({id: "div_resizable"});
To set a property on the first element inside a jQuery result object:
div_resizable = $( "#child" ).parent()[0];
// ^^^
div_resizable.id = "div_resizable";
This picks the first Element from the result so that you can directly access the property.
Or:
$('#child').parent().prop('id', 'div_resizable');
Use the .prop() helper method to accomplish the same thing.

Unable to replace the class of div element - no method named css

I want to replace the old class of html element with the new one using jQuery. Here is what I'm doing:
var elem = $('.my_selector')[0];
elem.css('class', 'my_new_class');
But I get the error saying "Uncaught type error: Object#<HtmlDivElement> has no method css.
How do I fix it?
The problem is that you are trying to call jQuery method css() (even not relevant here) from DOM element, which is derived with [0]. You can use toggleClass() to do the job:
$(".my_selector:first").toggleClass("my_selector my_new_class");
$('.my_selector')[0] is returning you a DOM element, not a jQuery Object. You'll also want to use the addClass method rather than css. To get the first element, you can use the :first pseudoselector.
So this should be what you are looking for:
$('.my_selector:first').removeClass('my_selector').addClass('my_new_class');
EDIT You can use either removeClass/addClass or toggleClass. Either are fine. Explicitly adding the new class may be safer if you have a case where an element can have both classes at the same time since toggleClass will remove both classes.
var elem = $('.my_selector')[0];
This will return the DOM element, not a jQuery object. Simply change it to this...
var elem = $('.my_selector');
To get just the first element that matches the selector, use this...
var elem = $('.my_selector').first();
Also, you have...
elem.css('class', 'my_new_class');
This is incorrect and should be changed to this...
elem.attr('class', 'my_new_class');
Try this ,
var elem = $(".my_selector");
elem.class("newclass");
otherwise you can do,
var elem = $(".my_selector");
elem.removeClass("my_selector");
elem.addClass("newclass");
$(".my_selector").removeClass('currentClass').addClass('newClass');
As said, you need the jquery object of the first element. A good method could be this:
$('.my_selector').first().css('class', 'my_new_class');
Moreover the method signature is .css( propertyName, value ) so its intented to set a css property not to change a class. To do that you need to remove old class and add new one with .removeClass and .addClass respectively.
$($('.my_selector')[0]).css('class', 'my_new_class');
document.getElementsByClassName('my_selector')[0].className = 'my_new_class';

How to add text to a DIV from array of DIVs

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

Categories

Resources