简体   繁体   English

如何通过Javascript定位子div?

[英]How to target child div by Javascript?

I want to apply JavaScript on sticky header in my site.我想在我网站的粘性标题上应用 JavaScript。 For this I want to target a div inside sticky div by JavaScript.为此,我想通过 JavaScript 在粘性 div 中定位一个 div。 Please let me know how to target a dive that is inside some other divs by JavaScript.请让我知道如何通过 JavaScript 定位其他 div 中的潜水。

 var yourHTML = '<div class="mynewdiv">Test</div>'; document.getElementsByClassName('at-sticky' 'custom-logo-link') [0].innerHTML = yourHTML;
 <div class="at-sticky"> <div class="container"> <div class="navbar-header"> <a href="#" class="custom-logo-link" rel="home" itemprop="url"> <img src="#" class="custom-logo"> </a> </div> </div> </div>

You can try with Document​.query​Selector() which allows CSS like selector:您可以尝试使用Document​.query​Selector() ,它允许 CSS 之类的选择器:

 var yourHTML = '<div class="mynewdiv">Test</div>'; document.querySelector('.at-sticky .custom-logo-link').innerHTML = yourHTML;
 <div class="at-sticky"> <div class="container"> <div class="navbar-header"> <a href="#" class="custom-logo-link" rel="home" itemprop="url"> <img src="#" class="custom-logo"> </a> </div> </div> </div>

Please use querySelector()

var yourHTML = '<div class="mynewdiv">Test</div>';
document.querySelector('.at-sticky .custom-logo-link').innerHTML = yourHTML;

Simplest solution is using querySelector最简单的解决方案是使用querySelector

Example :示例

document.querySelector('.at-sticky .container .custom-logo-link').innerHTML = yourHTML

请在类名之间添加逗号:

document.getElementsByClassName('at-sticky', 'custom-logo-link')[0].innerHTML = yourHTML;

Ok 2 points: Firstly when using innerHTML you are inserting text into your element, not the full tag as you have done.好的 2 点:首先,当使用 innerHTML 时,您将文本插入到元素中,而不是像您所做的那样插入完整的标签。 Secondly you only need pass in to 'document.getElementsByClassnames' the class name that you are targeting.其次,您只需要向“document.getElementsByClassnames”传递您所针对的类名。 Dont worry about the parent div, that should work fine as is.不要担心父 div,它应该可以正常工作。 I would have posted a comment but I don't have enough reputation yet;)我会发表评论,但我还没有足够的声誉;)

您可以为此使用 children() 函数。

$('.at-sticky').children();

You can use querySelector for this.您可以为此使用 querySelector。

Let's say you have the following HTML structure假设您有以下 HTML 结构

<div class="parentDiv">
  <a href="#"></a>
</div>

Then you can do this in JavaScript然后你可以在 JavaScript 中做到这一点

let parentDiv = document.querySelector('.parentDiv')
let childLink = parentDiv.querySelector('a')

console.log(childLink)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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