Is it possible to generate comments for closing div tags, lets take this ex. into consideration normal HTML:
<div id="content">
...
...buch of html or whateve
</div>
with comments :
<div id="content">
...
...buch of html or whateve
</div><!--End of content-->
and so on go trough each div element and comment the end of it ?
Here is a possible solution, in PHP, using DOM :
Using PHP allows you to save it, or whatever you need to ; and as it's using DOM, which is quite standardized, translating this to another language shouldn't require too much work.
(And, judging from a comment on your question, you didn't exclude other languages that JS)
$html = <<<HTML
<div id="content">
...
...buch of html or whateve
</div>
HTML;
$dom = new DOMDocument();
$dom->loadHTML($html);
$divs = $dom->getElementsByTagName('div');
for ($i = $divs->length - 1 ; $i > -1 ; $i--) {
$div = $divs->item($i);
if ($div->hasAttribute('id')) {
$id = $div->getAttribute('id');
$comment = $dom->createComment("End of {$id}");
if($div->nextSibling) {
$div->parentNode->insertBefore($comment, $div->nextSibling);
} else {
$div->parentNode->appendChild($comment);
}
}
}
echo $dom->saveHTML();
Which gets you the following HTML source :
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<div id="content">
...
...buch of html or whateve
</div>
<!--End of content-->
</body></html>
A couple of things to note :
DOM allows one to load and parse non-valid HTML
And generates valid-HTML
And, about what this does :
Load the HTMl string, using DOMDocument
Search for all <div> tags
Foreach <div> tag :
If it has an id attributes,
Get its value
Create a comment based on that value
And add it to the DOM, after the </div> tag
Another solution, thinking about it, would probably have been to use XPath, instead of getElementsByTagName + hasAttribute...
using jQuery, this is very simple.
jQuery('div').after('<!--end of content-->');
EDIT:
jQuery('div').each(function(){ jQuery(this).after('<!-- end of '+jQuery(this).id + '-->');});
var divs = document.getElementsByTagName("div");
for (var d = divs.length-1; d >= 0; --d) {
var div = divs[d];
var id = div.id; // d.getAttribute("id")
if (id) {
var cmt = document.createComment("End of " + id);
div.parentNode.insertBefore(cmt, div.nextSibling);
}
}
Related
This question already has answers here:
Hiding a Div using php
(6 answers)
Closed 1 year ago.
I want to show and hide a div based on a condition. This time I am not using any function since I thought it would be better as simple as possible.
I am trying to show and hide 2 DIVs based on a "status" of the user ($new). I don't know if it's possible to assign a PHP value to a JavaScript variable and the best way to do it ...
"var" is supposed to get the value of "$new".
Javascript:
<script>
var var = $new;
if (var != 1) {
document.getElementById("subjectr").style.display = "block";
} else {
document.getElementById("subjectr").style.display = "none";
}
</script>
HTML:
<center>
<div id="subjectr" value="<?php echo "$new"?>" style="display: none">
COORDINADOR
</div>
</center>
If you know a better way to do it, I would appreciate your help.
You don't need JS, simply echo or wrap the desired HTML into an if $new is true right on the server-side
Using PHP
<?php if ($new) { ?>
<div>Content for new users</div>
<?php } ?>
Using CSS (and PHP)
<div class="<?= $new ? '' : 'isHidden' ?>">Content for new users</div>
.isHidden { display: none; } /* Add this class to CSS file */
The above might come handy if at some point, by using JavaScript you want to toggle the visibility of such element using .classList.toggle('isHidden') or jQuery's .toggleClass('isHidden')
Using JavaScript (and PHP)
If you really want to pass your PHP variable to JavaScript:
<div id="subjectr">Content for new users</div>
<script>
var isNew = <?php echo json_encode($new); ?>;
document.getElementById("subjectr").style.display = isNew ? "block" : "none";
</script>
<!-- The above goes right before the closing </body> tag. -->
PS:
The <center> tag might work in some browsers but it's long time obsolete. Use CSS instead.
The value is an invalid HTML5 attribute for div Element. Use data-value instead.
What's doing the method=POST; on an <a> tag?
var var is a syntax Error in JavaScript, var being a reserved word. Use a more descriptive var isNew instead.
Instead of using javascript, you could use PHP to influence the display style of your div by using a ternary to decide whether it is none or block:
<center>
<div id="subjectr" value="<?=$new?>" style="display: <?=$new != 1 ? 'block' : 'none'?>">
COORDINADOR
</div>
</center>
For first, you should avoid to use var as a variable in your JS code, since it's an reserved key.
For your problem, revise your JS code:
<script>
var cond = document.getElementById('subjectr').getAttribute('value');
if (cond != 1) {
document.getElementById("subjectr").style.display = "block";
}
else {
document.getElementById("subjectr").style.display = "none";
}
</script>
You can get attribute result using getAttribute method in javascript, or attr method in jQuery.
A javascript variable can get the value of a PHP variable like so (assuming the PHP var is an integer):
var myvar = <?=$new?>;
Since you tag this as a PHP and a CSS issue, I think our mobile function is pretty near. This is our CSS "shownot" class:
.shownot { display: none !important; }
After, we use to hide certain cols on device mobiles, in your case the "$new" var:
<?php
$new = isMobile() ? 'shownot' : '' ;
?>
Finally, use as class whenever you need
<div id="subjectr" class="<?php echo $new;?>">
COORDINADOR
</div>
I am currently trying to place something like this https://shortdomain.com/api?p=a-href-url-here.com before every link on my website in a specific div.
$main = get_the_content_with_formatting();
$stripped = str_replace('<a href="http://example.net/', '<a href="https://shortdomain.com/api?p=http://example.net/', $main);
The method above works, but only when the link is that URL, and with any other it obviously will just return the standard URL.
Is there a way that I can prefix my desired link to each href using JavaScript, or PHP?
Here's the selector of the contents inside of $main
#the-post > div.post-inner > div.entry > p > strong > a
Don't ever make the mistake of parsing HTML like text; it's not! Use a proper DOM parser to extract your values and then alter them.
<?php
$main = "<div><p>Here is some <a href='http://example.com/'>sample</a> text.</p></div>";
$dom = new DomDocument();
$dom->loadHtml($main, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);
foreach ($dom->getElementsByTagName("a") as $anchor) {
$href = $anchor->getAttribute("href");
if ($href) {
$anchor->setAttribute("href", "https://shortdomain.com/api?p=" . urlencode($href));
}
}
echo $dom->saveHTML();
This is a good task for PHP's built-in DOMDocument and DOMXpath classes. Using xpath ensures that you only change anchors inside the div that you want.
$main = '<div class="post-inner"><div class="entry"><p><strong>link</strong></p></div></div>';
$doc = new DOMDocument();
$doc->loadHTML($main, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXpath($doc);
$anchors = $xpath->query('//div[contains(#class, "post-inner")]//a');
foreach ($anchors as $a) {
$a->setAttribute('href', 'https://shortdomain.com/api?p=' . $a->attributes->getNamedItem('href')->nodeValue);
}
echo $doc->saveHTML();
Output:
<div class="post-inner"><div class="entry"><p><strong>
link
</strong></p></div></div>
Demo on 3v4l.org
You can use the attribute selector with jquery to match all desired elements and then use the method 'attr' to change the href attribute.
$("#the-post > div.post-inner > div.entry > p > strong > a[href=\"http://example.net/\"]")
.attr("href", "https://shortdomain.com/api?p=http://example.net/");
I didn't really test it, but it should work just fine.
If you are doing this client-side, it's pretty painless with javascript's querySelectorAll:
let as = document.querySelectorAll('#the-post .post-inner .entry p strong a')
as.forEach(a => a.href ="https://shortdomain.com/api?p="+a.href)
Don't change
<div id="the-post">
<div class="post-inner">
<div class="entry">
<p>
change these:
<strong>
some inside <br />
some other inside
</strong></p>
</div>
</div>
</div>
Get rid of the dummy website then.
$main = get_the_content_with_formatting();
$stripped = str_replace('href="', 'href="https://shortdomain.com/api?p=', $main);
in DOM I already have a wrapper
<div id="wrapper"></div>
which I need to fill with bunch of divs, where each will represent new category.
Each category will be then filled with various cards representing items of that category. Like this:
<div id="wrapper">
<div data-category="puppy">
Dynamically created category wrapper
<div class="puppy1">...</div>
<div class="puppy2">...</div>
</div>
<div data-category="cat">
...
</div>
</div>
I use following code to create and fill category, but I always end up either having empty category or having a string inside reprenting the html.
var categoryWrapper = document.createElement("div");
categoryWrapper.setAttribute("data-category", key);
categoryWrapper.innerHtml = htmlString;
Here is a fiddle demo of my issue.
https://jsfiddle.net/uuqj4ad5/
I'll be grateful for a help.
There is a typo, innerHml should be innerHTML(Javascript object properties are case sensitive) otherwise it simply add an additional property and nothing gets happened.
categoryWrapper.innerHTML = htmlString;
var htmlString = "<div class='card'><div class='cardImg'><img src='http://cdn.cutestpaw.com/wp-content/uploads/2012/07/l-Wittle-puppy-yawning.jpg' alt='Puppy'></div><div class='cardContent'><div class='cardInfo'><p>Puppy Yawning</p></div><div class='cardDesc'><p>Awww!</p></div></div></div>";
var outerWrapper = $("#wrapper");
var categoryWrapper = document.createElement("div");
categoryWrapper.innerHTML = htmlString;
outerWrapper.append(categoryWrapper);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>
Under this title various categories should be dynamically created
</h3>
<div id="wrapper">outerWrapper waiting for dynamic data...</div>
</div>
FYI : If you want to remove the existing content then use html() method instead of append() method.
innerHtml
should be
innerHTML
Javascript is case sensitive
If you are using jQuery why do you want to mix jQuery and Vanilla JS.
var outerWrapper = $("#wrapper");
// I created new categoryWrapper object
var categoryWrapper = $('<div/>', {
html: htmlString
});
debugger;
// WHen I have the category filled with inner data, I will append it into outerwrapper
outerWrapper.append(categoryWrapper);
jsFiddle
Checkout my fiddle:-
https://jsfiddle.net/dhruv1992/1xg18a3f/1/
your js code should look like this
// This is dynamically filled html template. The data comes from some JSON.
var htmlString = "<div class='card'><div class='cardImg'><img src='http://cdn.cutestpaw.com/wp-content/uploads/2012/07/l-Wittle-puppy-yawning.jpg' alt='Puppy'></div><div class='cardContent'><div class='cardInfo'><p>Puppy Yawning</p></div><div class='cardDesc'><p>Awww!</p></div></div></div>";
// This outer wrapper will in the end contain few categories
var outerWrapper = $("#wrapper");
outerWrapper.append('<div>'+htmlString+'</div>')
I'm using uncode theme and I have a page heading that is showing 'Archive: Portfolio'
I want to remove the 'Archive:' bit from that heading.
In the source it looks like this:
<h1 class="header-title h1"><span>Archives: Projects</span></h1>
I have tried removing Archive from all the page titles with Yoast SEO plugin but it is still showing.
Is there a way to remove that word with javascript maybe does anyone know?
Thanks!
I'd be wary in removing it via javascript. It seems to me that adding a piece of text somewhere in the code's execution, and then removing it on the client-side smells like "contrived complexity".
Take a look at the wordpress template hierarchy, and manually search for the template file that's rendering the Archives: string of text.
I'd start with archive.php, and then fall my way up through other archive-*.php pages, then to taxonomy.php category.php, and so on.
If you're comfy in the command line, you might also consider grepping for the string: grep -r /path/to/wp/theme "Archive:" and sifting through the results to find the template file(s) with that on one of their lines.
But if you insist on removing the string via javascript, you might try dropping something like this at the bottom of the <body>, via a function in functions.php:
function remove_archive_text_via_js() {
if (is_archive()) { ?>
<script type="text/javascript">
var archiveHeaders = document.getElementsByClassName('header-title');
for (i = 0, headerCount = archiveHeaders.length; i < headerCount; i++) {
var replacedText = archiveHeaders[i].textContent.replace('Archives: ', '');
archiveHeaders[i].textContent = replacedText;
}
</script>
<?php }
}
add_action('wp_footer', 'remove_archive_text_via_js');
var elem = document.getElementsByClassName('header-title h1');
var innerSpan = elem[0].getElementsByTagName('span');
innerSpan[0].innerHTML = innerSpan[0].innerHTML.replace('Archives: ', 'jsfiddle');
jsfiddle: https://jsfiddle.net/orcadj3u/
$(function() {
$( "h1 span" ).each(function( index ) {
var newtext = $(this).text().replace("Archives: ", " ");
$(this).html(newtext);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h1 class="header-title h1"><span>Archives: Projects</span></h1><br>
<h1 class="header-title h1"><span>Archives: Solutions</span></h1><br>
<h1 class="header-title h1"><span>Archives: Yozgat</span></h1><br>
<h1 class="header-title h1"><span>Archives: Turkey</span></h1><br>
I have a div in which I have to fill some data in. I have to render the HTML based on conditions and I am adding data to that div using jQuery. Can someone please tell me how I can add the condition based insertion of HTML on the page?
function AddData()
{
var data = "<div><h1>My data</h1>"
if(jsVariable){
<p>The JSVariable is present on page </p>
}
+"</div>"
$('.myDiv').after("<br/>"+data);
}
function AddData()
{
var data = "<div><h1>My data</h1>"
if(jsVariable){
data = data + "<p>The JSVariable is present on page </p>"
}
data = data + "</div>"
$('.myDiv').append("<br/>"+data);
}
function AddData(){
if(typeOf(jsVariable)!=="undefined"){
var data = "<div><h1>My data</h1>";
data += " <p>The JSVariable is present on page </p>";
data += "</div>";
$('.myDiv').after("<br/>"+data);
}
}
this should do the trick, but some element with a class of myDiv will need to already exist for this to work
<div class="myDiv"></div>
What exactly are you trying to do?
If you simply want to add some extra html content depending on the variable, you are almost done. You just need to add the <p> part to the data (data += "<p>...</p>").
If you're trying to add all of the html based on the variable, put the if statement around the $(".myDiv").after (which should be $(".myDiv").append btw).
You'r code is not valid.
Could you explain what do you want to do with
if(jsVariable){
<p>The JSVariable is present on page </p>
}
+"</div>"
If you want to add a html code at ending of a div, you should use
$('.myDiv').append('<p>Text text text text</p>');
simple usage:
<!DOCTYPE html>
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function() {
$("p").click(function() {
var a = $("#div1").text();
if (a == "one") {
$("#div2").text(a);
}
});
});
</script>
</head>
<body>
<div id="div1">one</div>
<div id="div2"></div>
<p>click me</p>
</body>
</html>
function addData(to)
{
var h1 = $('<h1>').text('My Data');
var data = $('<div>').append(h1);
if (window.jsVariable) {
$('<p>').text('JS Variable is present on the page').appendTo(data);
}
to.append(data);
}
addData( $('.myDiv') );
if (condition) {
$('div#yourDivID').html('<p>The JSVariable is present on page </p>');
}
In addition to .html(which places the html inside your div), you can use other things like append, prepend etc. Check out jQuery's documentation on DOM Insertion.
Here is a JSFiddle http://jsfiddle.net/va4n8/
function addData() {
var newDiv = $('<div>');
newDiv.append($('<h1>').html('My data'));
if ('jsVariable' in window) {
newDiv.append($('<p>').html('The JSVariable is present on page'));
}
$('.mydiv').after($('<br>')).after(newDiv);
}