Load static HTML file and split into array by class - javascript

I have been working on this for days and I get close but not all the way. Most of the SO answers I have found, help me get the file contents loaded into a div or a variable but it doesn't let me then do querySelectorAll on it. So, what I need to do is load the file and then break it up into an array based on a class. Without further ado, the code:
content.txt:
<h3 class="chapter">Chapter 1</h3>
<p>Lorem</p>
<h3 class="chapter">Chapter 2</h3>
<p>Lorem</p>
Loading JS:
$.ajax({
url: "content/content.txt",
cache: false,
crossDomain: true,
success: function(html){
var div = document.createElement("div");
div.innerHTML = html;
var chapters = div.querySelectorAll('chapter');
alert(chapters.length);
}
});
Expected Result:
['<h3 class="chapter">Chapter 1</h3><p>Lorem</p>',
'<h3 class="chapter">Chapter 2</h3><p>Lorem</p>']
So this loads the file (confirmed) and I have the html in a variable. I try loading it into a dynamic DIV in the DOM to do a querySelectorAll but all it returns is {}. If I dump the innerHTML all of my content is there.
I know I am mixing vanilla JS with jQuery, but I am unsure of the proper jQuery way to go about this. Any thoughts?

The selector chapter will match all your <chapter> elements. There is no such element in HTML and there is no such element in your text file. That is why nothing matches.
align="chapter" is invalid HTML. chapter is not a valid value for the align attribute, which is obsolete anyway.
Start by writing sensible HTML. Use a class to distinguish between types of div elements.
<div class="chapter">
For that matter, consider using the <section> element instead.
Then use a class selector (instead of a type selector):
div.querySelectorAll('.chapter');

Related

Changing inner HTML of a button with dynamic id

On a project I'm working on, a HTML file is defining a Javascript template used on selection buttons. All buttons have a "Change..." label that I want to localize (set dynamically). In other cases I'm searching for the element ID and setting the InnerHTML accordingly. But in this case, the ID of the buttons are defined dynamically. Is it possible to have a text element inside the button element, search for this element, and set its InnerHTML value?
<script id="optionSelectionTemplate" type="text/x-handlebars-template">
<div class="sub-section option-selection">
{{#if name}}<h4>{{name}}</h4>{{/if}}
<div class="current"></div><button class="button" id="{{id}}" data-action-id="{{id}}">Change...</button>
</div>
</script>
I've been searching this for a while now. But given that my forte is not web development, I'm not really sure what to search for...
You may be able to get the button element(s) by its class instead; for example:
var x = document.getElementsByClassName("button");
As you suggested, you can improve your selection's precision by first getting the 'optionSelectionTemplate' element(s) like so:
var x = document.getElementById("optionSelectionTemplate").getElementsByClassName("button");
Or if you prefer:
var x = document.getElementById("optionSelectionTemplate").getElementsByTagName("button");
Here are some links for more on these method:
https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
https://www.w3schools.com/jsref/met_document_getelementsbytagname.asp
Depending on how dynamic your localization should become, you could also specify the text inside a (locale-dependent) CSS as in https://jsfiddle.net/1gws5kat/ :
[HTML]
<button class="button btn_change" id="{{id}}" data-action-id="{{id}}"></button>
[CSS]
.btn_change:before { content: "Change..."; }
In particular when dealing with a large number of identically-named elements (i.e. many "Change" buttons), this might be pretty handy.
You find those btns by this command:
var btnlist= $(':button')
This Camano get you all button in your html file, then loop ton in and apply your changing.
Before call this command, jquery must be install.

jQuery replace multiple texts

I need some advice for my text replacement using jQuery. I have a template that looks like this and builds a shoppingcart:
{foreach from=$cart.products item=product}
<div class="product">
<span class="product-image"><img src="{$product.cover.small.url}"></span>
<div class="product-details">
<h2 class="name-header">{$product.name}</h2>
<div class="product-quantity-details">
<span class="quantity">{$product.quantity}</span>
This will give me a container for each product, there are more elements after and before. I have some buttons that can increase or decrease the quantity (.product-quantity-details .quantity). I use jQuery to send an AJAX request:
document.getElementById('link1').addEventListener('click', function(ev){
ev.preventDefault();
var html ;
$.ajax({
url: this.href,
type: "GET",
dataType: "html",
success: function(data) {
html = $(data).find('.product-quantity-details .quantity').html();
console.log(html);
$(".product-quantity-details .quantity").text(html);
}
});
});
The server returns a HTML representation of the whole cart (including the other items not shown in the code above). I cannot simply replace the container with the response, because there are images loaded and they don't appear if I use jQuery.replaceWith(). So currently I only can update one quantity.
Is there a way to update each quantity, so get an array of values from $(data).find('.product-quantity-details .quantity').html(); where I can iterate trhough and replace the exisiting text in the HTML?
Or is there a better way to achieve my gaol (update any amount of quantities in my HTML).
I thought of simply using html = $(data).find('.product-quantity-details .quantity');, is there a guarantee that this array has the order of the HTML elements?
simply use, I have not encountered any case where html elements order is not maintained. Also you have index property which will give the position number.
html = $(data).find('.product-quantity-details .quantity');

Remove any specific html code using javascript

In the past I used Google Developer Console to delete some specific divs on a page. I could do it manually of course but in some cases where the divs where many I had to use the console. I had a single line code that did the job (I found it while searching the internet) but I lost my note.
So how can I delete using javascript any html code (by copy pasting the code).
Something like:
elements = $('<div ... </div>');
elements.remove();
OR
$('<div ... </div>').remove();
Any ideas? I am not an expert in javascript (obviously) and I've been searching stackoverflow for hours without finding anything that works.
UPDATE: I think some people might get confused with my question. Google developer console accepts javascript command lines. So even though I ask for javascript I will use the code on the google developer console.
UPDATE 2 :
Here is an example of a div I need to delete. Keep in mind I want to copy paste the entire code in the javascript code. Not just identify the div.
<div class="entry-status-overlay" data-entry-status="declined">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">Declined</span>
</div>
</div>
It's the data-entry-status="declined" that makes that div unique so I can't just identify the div using an id selector or a class selector. I need to put the entrire thing there and remove it.
I tried:
$('<div class="entry-status-overlay" data-entry-status="declined"><div class="entry-status-overlay__inner"><span class="entry-status-overlay__title">Declined</span></div></div>').remove();
It didn't remove the div.
Try to search the dom by its outerHTML.
function deleteDomByHtml(html){
html=html.replace(/\s/g,'');
$("*").each(function(){
if(this.outerHTML.replace(/\s/g,'')===html){
$(this).remove();
}
});
}
And try this line on this page:
deleteDomByHtml(`<span class="-img _glyph">Stack Overflow</span>`);
You cannot do by simply pasting the code. That will remove all the div element.
You may need a specific selector like id,class or child to specific parent to remove the element from the dom.
Consider this case the divs have common class but the data-entry-status is different. So you can get the dom using a selector and then check the dataset property.
For demo I have put it inside setTimeout to show the difference. In application you can avoid it
setTimeout(function() {
document.querySelectorAll('.entry-status-overlay').forEach(function(item) {
let getStatus = item.dataset.entryStatus;
if (getStatus === 'declined') {
item.remove()
}
})
}, 2000)
<div class="entry-status-overlay" data-entry-status="declined">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">Declined</span>
</div>
</div>
<div class="entry-status-overlay" data-entry-status="accepted">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">accepted</span>
</div>
</div>
Just add any attribute with [] and it will remove the element.
$('[class="entry-status-overlay"]').remove();
/*OR*/
$('[data-entry-status="declined"]').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="entry-status-overlay" data-entry-status="declined">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">Declined</span>
</div>
</div>
function del(){
var h = document.body.outerHTML;
h = h.match('<div>...</div>');
h.length--;
return h;
}
I guess this will work just give it a try... i tried on browser console and it worked, this way you can match the exact you want.
I might as well add my take on this. Try running this in your console and see the question vanish.
// convert the whole page into string
let thePage = document.body.innerHTML,
string = [].map.call( thePage, function(node){
return node.textContent || node.innerText || "";
}).join("");
// I get some string. in this scenario the Question or you can set one yourself
let replacableCode = document.getElementsByClassName('post-layout')[0].innerHTML,
string2 = [].map.call( replacableCode, function(node){
return node.textContent || node.innerText || "";
}).join("");
// replace whole page with the removed innerHTML string with blank
document.body.innerHTML = thePage.replace(replacableCode,'');
If you want to identify divs with that particular data attribute, you can use a data-attribute selector. In the example below, I've used a button and click event to make the demo more visual, but in the console the only line you'd need would be:
$('div[data-entry-status="declined"]').remove();
$(function() {
$("#testbutton").click(function() {
$('div[data-entry-status="declined"]').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="entry-status-overlay" data-entry-status="declined">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">Declined</span>
</div>
</div>
<div id="x">Some other div</div>
<button type="button" id="testbutton">Click me to test removing the div</button>
See https://api.jquery.com/category/selectors/attribute-selectors/ for documentation of attribute selectors.
P.S. Your idea to paste some raw HTML into the jQuery constructor and then execute "remove" on it cannot work - you're telling jQuery to create an object based on a HTML string, which is, as far as it's concerned, a new set of HTML. It does not try to match that to something existing on the page, even if that exact HTML is in the DOM somewhere, it pays it no attention. It treats what you just gave it as being totally independent. So then when you run .remove() on that new HTML...that HTML was never added to the page, so it cannot be removed. Therefore .remove() has no effect in that situation.

Accessing data of div with class 'note-editable ' of summer-note editor div

I want to access the text written in summer-note editor to save it into the database.
I am using summer note for my blog site, but I am not able to access the data of the div with class name note-editable..
This is the code of the div I'd like to access:
<div class="note-editable" contenteditable="true" style="height: 510px;">
hi...Write an amazing Post....
</div>
anyone knows how to achieve it ..thanks in advance....
Just see what the developers have set in place for this task: (from summernote.org):
get & set Code
Get the HTML contents of the first summernote in the set of matched
elements.
var sHTML = $('.summernote').code();
Get the HTML content of the second summernote with jQuery eq.
var sHTML = $('.summernote').eq(1).code();
A string of HTML to set as the content of each matched element.
$('.summernote').code(sHTML);
for more detail api: deep dive with api
What is wrong with this code? What you can obtain?
Just grab the element and then the text inside of it.
Like this:
var content = document.getElementsByClassName('note-editable')[0];
console.log(content.innerHTML)
<div class="note-editable" contenteditable="true" style="height: 510px;">hi...Write an amazing Post....</div>
You can simply use innerText or .textContent properties to get the text inside your div:
var text = document.getElementsByClassName('note-editable')[0].innerText;
alert(text);
<div class="note-editable" contenteditable="true" style="height: 510px;">Hi...Write an amazing Post....</div>
Note:
Avoid using innerHTML because it will return the sub-elements HTML code also and referring to the innerHTML documentation:
If a <div>, <span>, or <noembed> node has a child text node that includes the characters (&), (<), or (>), innerHTML returns these characters as &amp, &lt and &gt respectively. Use Node.textContent to get a correct copy of these text nodes' contents.

replace content of div with another content

I've been building a list of links, all of which should change the content of a div to another specific content (about 4 lines of stuff: name, website, contact etc.) upon a click.
I found this code:
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
and used it in such a way:
<li class="pl11">
superlink')">Pomorskie</a>
</li>
And it doesn't work as I expected.
It changes hyperlinks text from 'Pomorskie' to 'superlink'.
The plain text works just fine but I need links.
here's the http://xn--pytyfundamentowe-jyc.pl/projektanci/kontakty-p/ (only two of them show anything)
But after trying all of your recomendations, I think I'd jump to different divs with #links, cause nothing worked with this :/
Thanks a lot for trying, and cheers :)
Just as a completely sideways look at this, I'd suggest avoiding the nesting weirdness / complexity, and reducing the problem down.
Setup the content in a hidden (ie. <div id="replacements">...</div>) Grab the innerHTML from the node you want, and be done with it.
Much easier to get replacement content from non-devs that way too, kinda works great if you're in a team.
// Probably better in a separate helpers.js file.
function replaceContentInContainer(target, source) {
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
Control it with: (lose that href=javascript: and use onClick, better as an event handler, but for brevity I'll inline it as an onClick attribute here, and use a button.)
<button onClick="replaceContentInContainer('target', 'replace_target')">Replace it</button>
We have our target somewhere in the document.
<div id="target">My content will be replaced</div>
Then the replacement content sits hidden inside a replacements div.
<div id="replacements" style="display:none">
<span id="replace_target">superlink</span>
</div>
Here it is in JSBin
Improve the dynamic nature of this by using Handlebars or another nice JS templating library, but that's an exercise for the OP.
edit: Note, you should also name functions with a leading lowercase letter, and reserve the leading uppercase style for Class names e.g. var mySweetInstance = new MySpecialObject();
The quotes are mismatched! So when you click you are getting a JavaScript error.
The browser sees this string:
href="javascript:ReplaceContentInContainer('wojewodztwo', 'superlink')">Pomorskie<
as:
href="javascript:ReplaceContentInContainer('wojewodztwo', '<a href="
Chnage the " inside to #quot;
<li class="pl11">
Pomorskie
</li>
Example fiddle.
Also note, using the href tag for JavaScript is a BAD practice.
You've got a problem with nested quotes. Take a look in your DOM inspector to see what the HTML parser built from it! (in this demo, for example)
You either need to HTML-escape the quotes inside the attribute as " or ", or convert them to apostrophes and escape them inside the JS string with backslashes:
<a href="j[…]r('wojewodztwo', '<a href="http://address.com">superlink</a>')">…
<a href="j[…]r('wojewodztwo', '<a href=\'http://address.com\'>superlink</a>')">…
See working demos here and here.
Better, you should use a onclick attribute instead of a javascript-pseudo-url:
<a onclick="ReplaceContentInContainer('wojewodztwo', …)">Pomorskie</a>
or even a javascript-registered event handler:
<li class="pl11">
<a id="superlink">Pomorskie</a>
</li>
<script type="text/javascript">
function replaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
document.getElementBId("superlink").onclick = function(event) {
replaceContentInContainer('wojewodztwo', 'superlink');
event.prevenDefault();
};
</script>
(demo)

Categories