简体   繁体   中英

How to replace custom HTML tag with another tag, using the same content?

Is it possible to create your own text contents (text between the HTML tags) of my custom HTML tags?

I used this code:

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
  <script>
    $(document).ready(function () {
      $("eg").replaceWith("<h2>Put the text content of eg here</h2>");
    });
  </script>
</head>
<body>
  <eg>My text</eg>
</body>
</html>

Between the <h2> tags (don't think I should only use <h2> tags without JS) in my JavaScript code, any text can be placed that I like to have.

Example: <eg>I can type any text here but it'll be still in h2 tag settings</eg> .

What should I write between <eg></eg> in JS to have any <h2> text content that will be written in my HTML code?

If you want to replace the <eg>Test</eg> with <h2>Test</h2> then you can just do this: $("eg").replaceWith("<h2>" + $("eg").html() + "</h2>"); .

Here is an example: http://plnkr.co/edit/urd69pJSXQngGIsYYSjq

If I'm understanding correctly, you just want to append an element to the DOM, so you can just use the html method as follows:

  $("eg").html("<h2>Any text can be placed here</h2>");

Have a look at the docs if you need more info.

Note: You closed but didn't open your body tag.

Replace:

</body> 

With something like:

<body> <eg> Your custom content is between body tags now </eg> </body>

And you also have two HTML tags, remove the second

<html> 

No. It wouldn't be HTML anymore. However, if you wrote xHTML (which is a form of XML), then you could extend the DOM with your own elements. But that would be XML , not HTML.

And if you tried adding custom elements to a page, browsers wouldn't know what to do with them. Even if some browsers might display them, it's a very bad idea. Use a class name instead.

Creating and using custom tags is a bad idea. It should be avoided.

You are probably looking for this:

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
    <script>
        $(document).ready(function () {
            $("#my_h2").html("<h2>Any text can be placed here</h2>");
        });
    </script>
</head>
    <h2 id="my_h2"></h2>
</body>
</html>

For more, read-up on CSS selectors. (They are the same as jQuery selectors.)

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM