I've got this element that's not precisely defined as a div or anything but just white space popping up inside the html. Can't get to it with jQuery to remove it.
Type of element is highlighted in the screenshot.
Im not expert, but maybe you could use .prev() method.
Something like
$('#main .content').prev();
Pure Javascript to select it:
var textNode = document.getElementById("main").getElementsByClassName("filter-navigation")[0].nextSibling;
and remove it:
textNode.parentElement.removeChild(textNode);
jQuery simplifies the selection a bit, but the removal has to be done the same way since jQuery doesn't like removing text nodes:
var textNode = $("#main").find("filter-navigation")[0].nextSibling;
textNode.parentElement.removeChild(textNode);
The answer is not simply.
jQuery can map objects with structure. It's very hard to catch just whitespaces as DOM elements and remove them.
I cant suggest 2 alternatives:
Use jQuery to get parent tag, extract innerHTML and user regex to remove "extra whitespaces" between tags:
$(document).ready(function(){
var container = $('.product-container');
container.html(container.html().replace(/>\s+</i, '><'))
});
Use css to clean how looks my content inside that tag as suggests thirtydog here
Hope this help!
Related
I'm trying to move an anchor tag from one element to another. When I do this, the only thing appended is the anchors href, not the element itself. Why is this and how can I fix it?
I need a solution in Javascript only as jQuery isn't being used
Thanks for any help!
Fidde: https://jsfiddle.net/p7g7mkxs/
What I've tried:
<p class="hello">hello</p>
<p class="hello">helloLINK</p>
var hello = document.querySelectorAll('.hello');
hello[0].insertAdjacentHTML('beforeEnd', hello[1].querySelectorAll('a')[0]);
I've also tried using different variations of selecting my elements, like getElementsByTagName or appending it differently with innerHTML - Everything I've tried has given me the same result.
You use insertAdjacentHTML with HTML (a string), not with an actual element. If you pass it an element, the element is converted to string (like String(theElement)). In the case of an HTMLAnchorElement, that means you just get the href. Proof:
console.log(
String(document.querySelector("a"))
);
Hey
To append an element to the end of another element's child list, use appendChild:
var hello = document.querySelectorAll('.hello');
hello[0].appendChild(hello[1].querySelector('a'));
(To insert it elsewhere, use insertBefore. Actually, you can use insertBefore in all cases if you like, just use null as the reference element when adding to the end.)
Also note that when you only want the first match, rather than querySelectorAll(/*...*/)[0], use querySelector(/*...*/), which returns the first match or null.
In addition to what #t-j-crowder said, you can also use outerHTML to accomplish the task:
var hello = document.querySelectorAll('.hello');
hello[0].insertAdjacentHTML('beforeEnd', hello[1].querySelectorAll('a')[0].outerHTML);
I need to change the text in a button but it's not working. This is what I've come up with thus far:
var newElemen = $(<button text='Text changed..'></button>);
document.append$(newElemen);
I've also prepared a jsFiddle example.
Don't spend too many horses on this.
You need to first look at how jQuery's selector works. It works similar to CSS selectors (if you're not familiar with that I suggest you start with something more basic).
If you need a quick review on jQuery syntax. In your example you need to use the element selector $('button') and then you'll want to apply the .text() function to change the text for the button. So if you put it together. You'll want to select the button and then apply the text() function, passing in the string you want to change the text to, to change it's text.
$('button').text('Insert Text Here');
Use .text method using button selector
$("button").text('Text changed..');
$('button').text('new text');
fiddle: http://jsfiddle.net/zLf3k/3/
jQuery selector must be String
created new DOM element when you use html element on jQuery selector
use $(document).append instead of document.append$
$('button').text('some text');
I'm using JQuery's .append() and .remove() functions to add and remove variables from a div.
So the div looks a little like this when things are inside:
<div id="list">
<a>var1</a>
<a>var2</a>
<a>var3</a>
</div>
The problem is when I use .remove() on something in the div, it leaves a space in the DOM. So it looks like this:
var1
var3
I understand why this is happening but is there a simple way to solve this with another JQuery function that might make the div output like this after I use .remove():
var1
var3
Or do I neeed to do something more complicated?
Because your element is actually surrounded in text nodes containing a newline, as it's what your html says. If you don't believe me: http://tinker.io/7f667/1
\n<a>var1</a>\n<a>var2</a>\n<a>var3</a>\n
You don't notice them in display because html isn't (usually) whitespace sensitive.
If you want to remove the surrounding newlines, then tell the DOM to remove them: http://tinker.io/7f667/2
//assuming `list` is your container, and `toRemove` is the element to be removed
list.removeChild(toRemove.previousSibling);
list.removeChild(toRemove.nextSibling);
list.removeChild(toRemove);
Should be trivial to turn that into jquery code if you choose. Just pay attention that the surrounding text nodes are not elements.
The simplest way would be to insert parent() in there to remove the parent container rather than only removing the variable.
So if your code was like this:
$(myVar).remove();
... change it to this:
$(myVar).parent().remove();
Something else you could do if you need to preserve the existance of that particular parent container (like you may be adding something back into it) is to append a class to the parent that hides the container (and consequently the variable you want to remove) but can be repopulated and made visible again later.
.deactivated { display:none; }
$(myVar).parent().addClass('deactivated');
... then later you could do this:
$(myVar).parent().html(newValue).removeClass('deactivated');
Having written all that, you should REALLY probably cache the parent itself as a separate variable.. but you get the idea.
<div id="list">
<a>var1</a>
<a>var2</a>
<a>var3</a>
</div>
<script type='text/javascript'>
var var_to_remove = "var2";
//the anchor with var2 should be removed
$("#list > a").each(function()
{
if($(this).text() == var_to_remove)
{
$(this).detach();
}
});
</script>
You would obviously probably want to change the jquery to make the var_to_remove not hard-coded..and I'm assuming you want it to be on a click handler or something but this is another way to do it...
I have successfully implemented finding and replacing some text with something else in the following way:
$(".class").html($(".class").html().replace(/\text\b/g, '<span class="newclass newclass2">new text</span>'));
When I apply this to my element 'class' it finds all the 'text' and replaces with 'new text' and everything relating to the new classes.
However, if I have more than one element on the page with the same class, it replaces all the classes with whatever text is in the first class.
For example, if my first class has the content "Hello everyone", when the script is applied to this class, it works fine. Any subsequent class of the same name is then replaced with "Hello everyone". These also have the function applied in the same way as the first occurrence of that class.
IE, it applies the script, then replicates this in every single class of the same name on the page.
I do not understand why it would do this, and rather renders the function pointless in many ways if it can't be used to change text throughout different sections without setting up new scripts and different classes.
Hopefully there is something simple at work here that I am not aware of, any help would be much appreciated.
Many thanks
Richard
That is the nature of class selectors--the .html(...) will replace the HTML of everything that matches the .class selector.
If you want to replace text in each individual .class element, you can use the .each function. (There are probably jQuerier ways, too.)
$(`.class`).each(function(n, el) {
var myHtml = $(this).html();
myHtml = mungeIt(myHtml);
$(this).html(myHtml);
});
If you want to select only an individual .class element, then you either (a) don't really want to be using classes, but IDs, or (b) need to understand enough of your structure or the context you wish to operate in to select only the targeted DOM element.
(And hope the structure or context doesn't change without a corresponding code update.)
You're specifying a class with the jQuery selector $(".class") That's what the period indicates. jQuery has a ton of selectors to choose from. A list is provided in the documentation here: http://api.jquery.com/category/selectors/
Also, I'd look at http://api.jquery.com/hasClass/ for your problem as you could then use if...then statements to not run into others
Dave is right about needing to use the .each method. We need to loop through each element at a time because .html() will only return the first element when there are multiple matches.
Try:
$('.class').each(function() {
$(this).html($(this).html().replace(/someWord/g,'withAnother'));
});
How do I get the HTML that makes up an element using Jquery or Javascript?
For example if I have an element that looks like
<div id="theDivIWant" class="aClassName" style="somestyle: "here"></div>
I can grab a reference to it using
var x = document.getElementById("theDivIWant")
or $("#theDivIWant")
but how can I actually retrieve the string?
"<div id="theDivIWant" class="aClassName" style="somestyle: "here"></div>"
the outerHTML property will give you what you want in IE; in webkit and firefox, you can get the innerHTML of the parent and filter it:
var whatYouWantPlusItsSiblings = $('#target').closest().html();
From there, you can strip the content you don't need. Alternatively, if you have control over the markup, you can surround your target with another well-known element and get that parent's innerHTML.
You could implement outerHTML with jQuery.
if it is the only child of its parent, this should work:
$('#theDivIWant').parent().html();
If it is not the only child, you may be able to combine the above code with some regex to extract only it from the results.