I'm attempting to make an automatic ToC that can be dropped on a page. All of the pages have h3 tags with id set already. All of the code I'm finding wants to create the id for the tags first, but the pages I'm working on already have tags.
Basically I just need the code to
Step through all h3s on the page and get the ID and the text.
Create links to each of the h3s using the ID and text Text
Here's the code I've tried:
$(document).ready(function() {
setTimeout(() => {
// Get ToC div
toc = document.getElementById("ToC"); //Add a header
tocHeader = document.createElement("h2");
tocHeader.innerText = "Table of contents";
toc.appendChild(tocHeader); // Get the h3 tags — ToC entries
$('h3').each(function() {
var headers = $(this).attr('id');
var name = $(this).text();
});
// For each h3
for (i = 0; i < headers.length; i++) {
tocListItem = document.createElement("li");
// a link for the h3
tocEntry = document.createElement("a");
tocEntry.setAttribute("href", "#" + name);
tocEntry.innerText = name[i];
tocListItem.appendChild(tocEntry);
tocList.appendChild(tocListItem);
}
toc.appendChild(tocList);
// Create a list for the ToC entries
tocList = document.createElement("ul");
}, 1000);
});
<body>
<div id="ToC"></div>
<div>
<h3 id="this-is-heading-1">First Heading</h1>
<p>
This is paragrah 1
</p>
<h3 id="another-heading">Second Section</h1>
<p>
This is some words
</p>
<h3 id="last-heading">And Finally</h1>
<p>
Some more verbiage
</p>
</div>
</body>
Simply you can go through of each h3 and get id attribute and then create link to corresponding element.
Try this one:
$(document).ready(function () {
setTimeout(() => {
// Get ToC div
toc = document.getElementById("ToC"); //Add a header
tocHeader = document.createElement("h2");
tocHeader.innerText = "Table of contents";
toc.appendChild(tocHeader); // Get the h3 tags — ToC entries
// Create a list for the ToC entries
tocList = document.createElement("ul");
$('h3').each(function () {
tocListItem = document.createElement("li");
// a link for the h3
tocEntry = document.createElement("a");
tocEntry.setAttribute("href", "#" + $(this).attr('id'));
tocEntry.innerText = $(this).text();
tocListItem.appendChild(tocEntry);
tocList.appendChild(tocListItem);
});
toc.appendChild(tocList);
});
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div id="ToC"></div>
<div>
<h3 id="this-is-heading-1">
First Heading
</h3>
<p>
This is paragrah 1
</p>
<h3 id="another-heading">
Second Section
</h3>
<p>
This is some words
</p>
<h3 id="last-heading">
And Finally
</h3>
<p>
Some more verbiage
</p>
</div>
Related
I want to loop multiple DIV elements.
There are 5 books. I want to loop 5 books in ID: BootLoop.
What I tried?
my_orders.append(data[i].order.bname).appendTo("#bookLoop > div > div > div > h3");
my_orders.append(data[i].order.blink).appendTo("#bookLoop > div > div > div > a");
It didn't work. Where am I making a mistake?
JS:
var my_orders = $("#bookLoop");
$.each(data, function(i, order) {
$("#bookName").append(data[i].order.bname);,
$("#bookURL").append(data[i].order.blink);
});
HTML (Code structure that should be loop):
<div id="bookLoop">
<div class="col-3">
<div class="block-content">
<div class="d-md-flex">
<h3 id="bookName" class="h4 font-w700"></h3>
<div>
<div class="d-md-flex link">
Details
<div>
<div>
<div>
<div>
JSON:
[
{"order":{"id":"61","bname":"Book 1","blink":984}},
{"order":{"id":"42","bname":"Book 2","blink":5414}},
{"order":{"id":"185","bname":"Book 3","blink":4521}},
{"order":{"id":"62","bname":"Book 4","blink":41254}},
{"order":{"id":"15","bname":"Book 5","blink":7464}}
]
I think that what you want is to append each book and link inside #bookLoop, beign each book and link with it's own content.
Below I'm creating elements (nodes) to each book you have then appending it to my_orders.
Take a look if it is what you want, if not, please edit your question showing an example of the desired rendered HTML
var my_orders = $("#bookLoop");
var books = ''
var links = ''
let data = [
{"order":{"id":"61","bname":"Book 1","blink":984}},
{"order":{"id":"42","bname":"Book 2","blink":5414}},
{"order":{"id":"185","bname":"Book 3","blink":4521}},
{"order":{"id":"62","bname":"Book 4","blink":41254}},
{"order":{"id":"15","bname":"Book 5","blink":7464}}
]
$.each(data, function(i, order) {
let col = document.createElement('div')
col.className = 'col-3'
let content = document.createElement('div')
content.className = 'block-content'
let flexC = document.createElement('div')
flexC.className = 'd-md-flex'
let title = document.createElement('h3')
title.className = 'h4 font-w700'
title.textContent = data[i].order.bname;
flexC.append(title)
let flexL = document.createElement('div')
flexL.className = 'd-md-flex link'
let details = document.createElement('a')
details.className = 'bookURL'
details.href = "#"
details.textContent = "Details: " + data[i].order.blink
flexL.append(details)
my_orders.append(col)
col.append(content)
content.append(flexC)
content.append(flexL)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="bookLoop">
<div>
Suppose I have this HTML:
<article id="1919">
<div class="entry-content clearfix">
<div></div>
<div></div>
</div>
</article>
<article id="1910">
<div class="entry-content clearfix">
<div></div>
<div></div>
</div>
</article>
I need to put a link in div with class "entry-content clearfix" for all articles
So can I do it JavaScript:
//take all div with these class value
var eventi_programma=document.getElementsByClassName('entry-content');
//for to read these elements
for(var i=0;i<eventi_programma.length;i++){
var link="http://www.google.it";//(LINK EXAMPLE);
eventi_programma[i].parentElement.innerHTML=''+eventi_programma[i].outerHTML+'</div>';
}
But my code doesn't work.
(function (){
var eventi_programma=document.getElementsByClassName('entry-content');
//for to read these elements
for(var i=0;i<eventi_programma.length;i++){
var link="http://www.google.it";//(LINK EXAMPLE);
eventi_programma[i].parentElement.innerHTML=' THIS IS A LINK </div>';
}
})();
It didn't work because you are putting eventi_programma[i].outerHTML as text of the link. As your for loop is based on .entry-content class it basicly creates a never ending for loop since you keep creating new divs with that classname. So instead of putting outerHTML put some other text.
I assume your entry-content class has only one in every article tag ! So I retrieve all article and added then replace it.
var eventi_programma = document.getElementsByTagName("article");
//for to read these elements
for(var i=0;i<eventi_programma.length;i++){
var link="http://www.google.it";//(LINK EXAMPLE);
org_html = eventi_programma[i].innerHTML;
new_html = "<a href='"+link+"'>" + org_html + "</a>";
eventi_programma[i].innerHTML = new_html;
}
//take all div with these class value
var eventi_programma = $('div.entry-content');
//for to read these elements
for (var i = 0; i < eventi_programma.length; i++) {
var link = "http://www.google.it";//(LINK EXAMPLE);
var temp = eventi_programma[i];
$(temp).parent('article').html('</div>')
}
try it...
Have a html string see below.
<div sentence="11">
<p>
how are you Tom, how are you Tom
</p>
</div>
<div sentence="12">
<p>
how are you Tom
</p>
</div>
When user select the name 'Tom', I will replace the string 'Tom' using a name tag with some html style. The result what I want see below.
<div sentence="11">
<p>
how are you <span class="ano-subject" data-oristr="Tom" data-offset="1" data-sentence="11"><NAME></span>, how are you <span class="ano-subject" data-oristr="Tom" data-offset="2" data-sentence="11"><NAME></span>
</p>
</div>
<div sentence="12">
<p>
how are you <span class="ano-subject" data-oristr="Tom" data-offset="1" data-sentence="12"><NAME></span>
</p>
</div>
I will using the code below to do the replace.
var content = HTML CODE ABOVE;
var selectText = 'Tom';
var regex = new RegExp('(?=\\s|^|\\b)(?:' + selectText + ')(?=\\s|$|\\b)', "g");
var pre_sentence = 0;
var offset = 0;
content = content.replace(regex, function(match, position) {
var curr_sentence = ???; // how can I get this element's parent div attribute 'sentence' ?
if(pre_sentence != cur_sentence){
// this is new sentence.
offset = 1;
pre_sentence = curr_sentence;
} else {
offset++;
}
var replace = '<span class="ano-subject" data-oristr="Tom" data-offset="'+offset+'" data-sentence="'+curr_sentence+'"><NAME></span>';
return replace;
});
I'm making an app that submits posts, but I originally designed it with a textarea in mind, I've since put in an iframe to create a rich text field, set the display style to hidden for the textarea and wanted to know how I could modify it to use the iframe value.
HTML
<div id="textWrap">
<div class="border">
<h1>Start Writing</h1><br />
<input id="title" placeholder="Title (Optional)">
<div id="editBtns">
<button onClick="iBold()">B</button>
<button onClick="iUnderline()">U</button>
<button onClick="iItalic()">I</button>
<button onClick="iHorizontalRule()">HR</button>
<button onClick="iLink()">Link</button>
<button onClick="iUnLink()">Unlink</button>
<button onClick="iImage()">Image</button>
</div>
<textarea id="entry" name="entry" rows="4" cols="50" type="text" maxlength="500" placeholder="Add stuff..."></textarea>
<iframe name="richTextField" id="richTextField"></iframe><br />
<button id="add">Submit</button>
<button id="removeAll" onclick="checkRemoval()">Delete All Entries</button>
<ul id="list"></ul>
<ul id="titleHead"></ul>
</div><!--end of border div-->
</div><!--end of textWrap-->
Here is the JS to submit the posts.
//target all necessary HTML elements
var ul = document.getElementById('list'),
removeAll = document.getElementById('removeAll'),
add = document.getElementById('add');
//richText = document.getElementById('richTextField').value;
//make something happen when clicking on 'submit'
add.onclick = function(){
addLi(ul)
};
//function for adding items
function addLi(targetUl){
var inputText = document.getElementById('entry').value, //grab input text (the new entry)
header = document.getElementById('title').value, //grab title text
li = document.createElement('li'), //create new entry/li inside ul
content = document.createElement('div'),
title = document.createElement('div'),
//textNode = document.createTextNode(inputText + ''), //create new text node and give it the 'entry' text
removeButton = document.createElement('button'); //create button to remove entries
content.setAttribute('class','content')
title.setAttribute('class','title')
content.innerHTML = inputText;
title.innerHTML = header;
if (inputText.split(' ').join(' ').length === 0) {
//check for empty inputs
alert ('No input');
return false;
}
removeButton.className = 'removeMe'; //add class to button for CSS
removeButton.innerHTML = 'Delete'; //add text to the remove button
removeButton.setAttribute('onclick', 'removeMe(this);'); //creates onclick event that triggers when entry is clicked
li.appendChild(title); //add title textnode to created li
li.appendChild(content); //add content textnode to created li
li.appendChild(removeButton); //add Remove button to created li
targetUl.appendChild(li); //add constructed li to the ul
}
//function to remove entries
function removeMe(item){
var deleteConfirm = confirm('Are you sure you want to delete this entry?');
if (deleteConfirm){var parent = item.parentElement;
parent.parentElement.removeChild(parent)}
};
function checkRemoval(){
var entryConfirm = confirm('Are you sure you want to delete all entries?');
if (entryConfirm){
ul.innerHTML = '';
}
};
demo I'm working on for reference.. http://codepen.io/Zancrash/pen/VemMxz
you can use either local storage for passing iframe values to the parent DOM.
or ( use this to pass value from iframe to parent container )
var iFrameValue = $('#iframe').get(0).contentWindow.myLocalFunction();
var iFrameValue = $('#iframe').get(0).contentWindow.myLocalVariable;
From IFrame html
<script type="text/javascript">
var myLocalVariable = "text";
function myLocalFunction () {
return "text";
}
</script>
I am unable to change the text inside my 'p' tag using this script
<script>
var firstItem = document.getElementByTagName('p');
firstItem.innerHTML = 'Adding Javascript';
</script>
You have several coding errors. Here's some corrected code:
<script>
var firstItem = document.getElementsByTagName('p')[0];
firstItem.innerHTML = 'Adding Javascript';
</script>
The correct method is document.getElementsByTagName('p'). Note the "s" at the end of "Elements".
Then, because document.getElementsByTagName('p') returns an HTML collection object, you have to either iterate over the collection or reach into the collection to grab a specific DOM object (which I did in my example with [0]).
And here's a working code snippet:
// change just the first <p> tag
document.getElementById("test1").addEventListener("click", function(e) {
var firstItem = document.getElementsByTagName('p')[0];
firstItem.innerHTML = 'Adding Javascript';
});
// change all the <p> tags
document.getElementById("test2").addEventListener("click", function(e) {
var items = document.getElementsByTagName('p');
for (var i = 0; i < items.length; i++) {
items[i].innerHTML = 'Setting All Items';
}
});
<button id="test1">Change text of first item</button><br><br>
<button id="test2">Change text of all items</button><br><br>
<p>This is some text</p>
<p>This is more text</p>
<p>This is and more text</p>